Efficient way to get middle (median) of an std::set?

后端 未结 5 1735
故里飘歌
故里飘歌 2021-01-07 23:52

std::set is a sorted tree. It provides begin and end methods so I can get minimum and maximum and lower_bound and u

5条回答
  •  梦毁少年i
    2021-01-08 00:12

    Depending on how often you insert/remove items versus look up the middle/median, a possibly more efficient solution than the obvious one is to keep a persistent iterator to the middle element and update it whenever you insert/delete items from the set. There are a bunch of edge cases which will need handling (odd vs even number of items, removing the middle item, empty set, etc.), but the basic idea would be that when you insert an item that's smaller than the current middle item, your middle iterator may need decrementing, whereas if you insert a larger one, you need to increment. It's the other way around for removals.

    At lookup time, this is of course O(1), but it also has an essentially O(1) cost at each insertion/deletion, i.e. O(N) after N insertions, which needs to be amortised across a sufficient number of lookups to make it more efficient than brute forcing.

提交回复
热议问题