Reputation: 3433
i have the following code which works perfect.
Objective: Given a number n, find the next and previous number of n.
Base on below example : if n = 50, then i will get 60 and 40 separately.
I am able to get 60 by using upper_bound. But how do i get a number before 50 i cant seem to find a provided algorithm to do that.
set<int> myset;
set<int>::iterator it,itlow,itup;
for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
itup=myset.upper_bound (50); //
cout << "upper_bound at position " << (*itup) << endl;
//output: 60
With reference to http://www.cplusplus.com/reference/stl/set/lower_bound/, it says upper_bound "Returns an iterator pointing to the first element in the container which does not compare less than x" but im sure there is something else that point to something that compare less than x.
Thanks in advance! :)
Upvotes: 5
Views: 1401
Reputation: 393863
Use lower_bound
like chris says see sgi: http://www.sgi.com/tech/stl/lower_bound.html and MSDN: http://msdn.microsoft.com/en-us/library/awxks70z%28v=vs.80%29.aspx.
lower_bound
will return the position where insertion will occur such that the order is maintained which is what you want.
So
itlow = myset.lower_bound (50); // check if this is not pointing to myset.end()
--itlow; // should still check if this is in your container really
cout << "upper_bound at position " << (*itup) << "lower bound" << (*itlow) << endl;
better version I think
// check whether lower_bound returns myset.end() or myset.begin() for sensible and safe assignment
if (myset.lower_bound(50) != myset.end() && myset.lower_bound(50) != myset.begin())
{
itlow = myset.lower_bound(50);
--itlow;
}
Upvotes: 1
Reputation: 18954
You want lower_bound(49)
. Or possibly do lower_bound(50)
and be prepared to go back one if needed.
Upvotes: 1
Reputation: 103693
it = myset.lower_bound(50);
--it;
Of course, don't dereference that iterator unless you are sure there is an element less than 50 in the set. You can check if it == myset.begin()
for that.
Upvotes: 6