Assuming a I have an STL set <int> s
and an int x
, how can I count the number of elements in s
that are less than x
?
I'm seeking an O(log n)
(or similar; anything that's reasonably better than O(n)
) solution;
I already know about std::distance(s.begin(), s.lower_bound(x))
, but that's O(n)
, I believe, because set
s aren't random-access.
The formula n(A U B) = n(A) + n(B) - n(A n B) describes how to count elements in two sets that intersect. We can also use Venn diagrams to help us count elements in sets, and they are especially useful when we are considering more than two sets.
C++ set lower_bound() C++ set lower_bound() function is used to return an iterator pointing to the key in the set container which is equivalent to val passed in the parameter. If val is not present in the set container, it returns an iterator pointing to the immediate next element which is just greater than val.
As mentioned above, sets in C++ are the type of STL containers that are used for storing elements in a sorted way. The operations allowed to be performed on sets are insertion and deletion. The elements are internally sorted according to a strict weak ordering in a set type container.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With