Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using STL Container set upper_bound

Tags:

c++

set

stl

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! :)

like image 606
mister Avatar asked May 12 '12 20:05

mister


1 Answers

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.

like image 148
Benjamin Lindley Avatar answered Sep 20 '22 02:09

Benjamin Lindley