Assuming a I have an STL set
and an int x
, how can I count the number of elements in s
that are less than x
What you need is an 'order-statistics tree'. It is essentially an augmented (binary search) tree that supports the additional operation rank(x)
which gives you the number of elements with less or equal key as element x
. Chapter 14 in Cormen, Leiserson, Rivest, Stein; "Introduction to Algorithms" should give you the algorithmic background.
There is also some implementation on the web.
As a follow up to my comment: using red-black binary search trees (instead of sets), if each node stores the number of nodes rooted in that node (updated every time you insert/delete a node) then you can get at "number of nodes more than/less than X" statistics quite fast.
I don't think that's possible. Your STL set is a tree-based structure, so even just checking an element's presence is O(log n). Your tree's nodes do not store their subbranches' sizes in any field (as far as I know), so the number of operations needed for counting nodes that have some property which does not follow directly from the rules used for building the tree cannot be smaller than the number of these nodes. Since you don't know in advance how many nodes have values smaller than x, the worst-case performance is when all nodes are smaller than x, which means O(n) worst-case complexity. Even if value x was in the tree, you need O(log n) operations to find that node but then need to visit all its left descendands in order to count them, so the complexity depends on the number of matching nodes which is O(n) in worst case. Perhaps with additional data in the tree's nodes, one could do better than that.