c++multiset

Just greater element or just smaller element in a multiset


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?


Solution

  • 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;
    }