Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With a STL map/set/multiset/multimap, How to find the first value greater than or equal to the search key?

Suppose I have a set of values, stored in a std::set:

{1, 2, 6, 8}

and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6.

The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. Is there a similar function to find that would return 6 in this case?

like image 572
Doug T. Avatar asked Dec 04 '22 16:12

Doug T.


1 Answers

Yes: upper_bound(X) returns an iterator pointing to the first element greater than X. There is also a lower_bound(X) function which returns an iterator pointing to the first element not less than X. Thus, all of the elements in the half-open interval [lower_bound(X), upper_bound(X)) will be equal to X.

like image 118
Adam Rosenfield Avatar answered Dec 26 '22 15:12

Adam Rosenfield