12

I have a set<int> and I want to see how many elements in it are less than x. (x is also int)

What should i do?

hivert
  • 10,579
  • 3
  • 31
  • 56

1 Answers1

20

Use lower_bound to compute std::distance(s.begin(), s.lower_bound(x)). (If x is a key, this counts the number of elements strictly before x.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 8
    Relevant link pertaining to the complexity of this solution: http://stackoverflow.com/questions/15321013/c-set-counting-elements-less-than-a-value – Thomas Eding Mar 06 '14 at 16:31
  • 10
    Yup, it's O(n) which isn't nice at all – Lev Leontev Oct 07 '19 at 15:11
  • 2
    @LeoLeontev: well, it's O(n) in iterator increments, not in applications of the predicate. If this sort of counting is your hot path, then you may prefer a "flat set" implementation where your iterators are random-access and you can compute differences in constant time. – Kerrek SB Oct 07 '19 at 17:42