Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the first value less than the search key with STL set?

Tags:

c++

stl

For example I have set of values in std::set:

{1, 2, 3, 5, 6}

And a search key, let it be 4, I want to find the first val. less than search key, 3 in this case, how to do it?

In Java there're functions greater(), lower() in TreeSet

like image 515
milos Avatar asked Apr 11 '14 11:04

milos


1 Answers

Simply find the lower_bound for that key and then decrement it once.

set<int> a;
set<int>::iterator it = a.lower_bound(5);
if (it != a.begin()) {
  it--;
  cout << *it << endl;
} else {
  cout << "No smaller element found!" << endl;
}

You can find a complete example here.

like image 109
Ivaylo Strandjev Avatar answered Nov 13 '22 23:11

Ivaylo Strandjev