Christopher Miller
Christopher Miller

Reputation: 3461

Is there a std::set function for determining the largest element that does not exceed a number x?

I read online that an std::set has useful member functions that can help search for elements.

Specifically,

std::set::lower_bound, which returns an iterator to the smallest element that is >= a number x, and
std::set::upper_bound, which returns an iterator to the smallest element that exceeds x.

However, I want to find a function that returns an iterator to the largest element that does not exceed x. Is there such a function in C++?

Upvotes: 0

Views: 589

Answers (1)

selbie
selbie

Reputation: 104549

Decrement the iterator returned from upper_bound:

std::set<int> s;
s.insert(3);
s.insert(4);
s.insert(5);
s.insert(7);

auto itor = s.upper_bound(6);
if (itor != s.begin())
{
    --itor;
    std::cout << *itor << std::endl;
}

The above should print "5"

Upvotes: 3

Related Questions