C ++ set: counting elements less than value

Assuming I have an STL set <int> sand int xhow can I count the number of elements in swhich are smaller x?

I am looking for a solution O(log n)(or the like, which is better than O(n));

I already know about std::distance(s.begin(), s.lower_bound(x)), but I believe that O(n), because it is setnot random access.

+24
source share
3 answers

What you need is a "custom statistics tree". This is essentially an extended tree (binary search) that supports an additional operation rank(x)that gives you the number of elements with a smaller or equal key as an element x. Chapter 14 in Cormen, Leyserson, Rivest, Stein; An Introduction to Algorithms should give you an algorithmic background.

There is also a web implementation .

+15
source

, . STL- - , - O (log n). ( ), , , , , , . , , , x, - x, O (n) . x , O (log n), node, , , , O (n) . , .

+7

As a comment to my comment: using red-black binary search trees (instead of sets), if each node stores the number of nodes embedded in this node (updated every time you insert / delete node), you can get statistics "number of nodes more or less X "pretty fast.

+6
source

All Articles