Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ set: counting elements less than a value

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 sets aren't random-access.

like image 639
Chris Avatar asked Mar 10 '13 10:03

Chris


People also ask

How do you count the number of elements in a set?

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.

How do you find the index in lower bound of a set?

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.

What is set <> in C++?

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.


1 Answers

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.

like image 79
DennisL Avatar answered Sep 23 '22 00:09

DennisL