user12345
user12345

Reputation: 45

lower_bound in set (C++)

I've got a set and I want to find the largest number not greater than x in it. (something like lower_bound(x) ) how should i do it? Is there any predefined functions?

set<int> myset;
myset.insert(blahblahblah);
int y;
//I want y to be greatest number in myset not greater than x

Upvotes: 3

Views: 3338

Answers (2)

CashCow
CashCow

Reputation: 31435

In addition to lower_bound there is also upper_bound C++ reference

The function returns an iterator to the first value that is strictly greater than yours. If it returns begin() then all of them are, otherwise subtract one from the resulting iterator to get the value you are looking for.

Upvotes: 0

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76788

You can use upper_bound like this: upper_bound(x)--. Upper bound gives you the first element greater than x, so the element you seek is the one before that. You need a special case if upper_bound returns begin().

Upvotes: 1

Related Questions