How do I find just greater or just smaller element than a particular element in a multiset? For example, I have inserted some elements in a multiset, now I want to find the elements just smaller and just greater than some element that I have already inserted, how do I do that?
Asked
Active
Viewed 723 times
2 Answers
0
You can use lower_bound and upper_bound as -
// multiset::lower_bound/upper_bound
#include <iostream>
#include <set>
using namespace std;
int main ()
{
std::multiset<int> mymultiset;
std::multiset<int>::iterator itlow,itup;
for (int i=1; i<8; i++) mymultiset.insert(i*10);
itlow = mymultiset.lower_bound (30); // ^
std::cout << "mymultiset less then 30:";
for (auto it=mymultiset.begin(); it!=itlow; ++it)
std::cout << ' ' << *it;
cout<<endl;
itup = mymultiset.upper_bound (40); // ^
std::cout << "mymultiset greater then 40:";
for (; itup!=mymultiset.end(); ++itup)
std::cout << ' ' << *itup;
cout<<endl;
return 0;
}

user1438832
- 493
- 3
- 10
-
Hi, thanks a lot, I have another doubt. let's say: itlow=mymultiset.lower_bound(30); itup=mymultiset.upper_bound(30); cout<<*itlow<<" "<<*itup; Why does it print "30 40" and not "20 40" – aroma Feb 28 '17 at 07:02
-
lower_bound Returns an iterator pointing to the first element in the container which is not considered to go before val (i.e., either it is equivalent or goes after). So ,all the elemnts upto itlow are less then. But itlow may contain equal val. – user1438832 Feb 28 '17 at 07:07
0
This is a similar question: https://codeforces.com/blog/entry/68036
For just bigger element - (considering name of multiset as ms) use ms.upper_bound(x)
to get an iterator and if ms.upper_bound(x)!=ms.end()
, the element is *ms.upper_bound(x)
For just equal or bigger element use lower_bound
as mentioned above
For just lower element first find an iterator ms.find(x)
and if ms.find(x)!=ms.begin()
, the element is *(--ms.find(x))

Sundaram Anand
- 1
- 1