Find a specific element in a set

I have a set<int> s and I want to find the greatest number in the set that is smaller than an int x.
So, this is my way (kind of):
1
2
3
4
5
6
7
8
9
set<int>::iterator it=(s.insert(x)).first;
if (it==s.begin()){
   //inform that no such number exists
   }
else { it--; 
   // inform that the number is (*it)
   }

// if (x was not in set s) s.erase(x); 


Is there any better way? I find this a little complicated :(
Thanks beforehand ^^
Last edited on
Thanks. Nice one. It's really helpful.
It's kind of tricky. To find the smallest number in set that is greater than x, I just use s.upper_bound(x). But to find the greatest number that is strictly smaller than x, I have to do it more complex:
1
2
3
4
5
6
7
8
9
// there is a set<int> s
set<int>::iterator it=s.lower_bound(x);
if (s.empty() || it==s.begin()){
   // inform that no such number number exists
   }
else {
   it--;
   // inform that the number is (*it)
   }


Is there any better way? (easy like the smallest but greater than x)
I wouldn't call that tricky.. You would need error checking whatever you did, and apart from that it only adds "it--". You can easily put this in a function.
Thanks. This site is really great for a beginner like me :D
Topic archived. No new replies allowed.