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! :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With