views:

1185

answers:

3

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?

+3  A: 

You want the upper_bound function.

map<int, int> mymap = { 1,2,6,8 };
map<int,int>::iterator i = mymap.upper_bound(3); // returns an iterator to the '6' element.
gbjbaanb
+2  A: 

lower_bound.

Oops, I meant lower_bound, the member function, not the algorithm.

If there's nothing in the set that's greater than or equal to your search item, it will return end().

Mark Ransom
+10  A: 

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.

Adam Rosenfield
Not "equal to X" but equivalent. For instance, in a case-insensitive set<string>, the lower_bound of "ABC" may be "abc". And for a std::set, "all elements in the half-open interval" will be at most 1 element.
MSalters