Assuming I have an STL set <int> sand int xhow can I count the number of elements in swhich are smaller x?
set <int> s
int x
s
x
I am looking for a solution O(log n)(or the like, which is better than O(n));
O(log n)
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.
std::distance(s.begin(), s.lower_bound(x))
set
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.
rank(x)
There is also a web implementation .
, . STL- - , - O (log n). ( ), , , , , , . , , , x, - x, O (n) . x , O (log n), node, , , , O (n) . , .
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.