Skip to content
Related Articles

Related Articles

Improve Article
multiset value_comp() method in C++ STL
  • Last Updated : 30 Oct, 2018

The std::multiset::value_comp is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container.By default, this is a less object, which returns the same as operator ‘<'.It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or false otherwise.Two keys are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).

Syntax:

value_compare multiset_name.value_comp() 

Parameters: This function does not accept any parameter.

Return value: The function returns a copy of the comparison object used by the container.

Below examples illustrate the above method:



Example 1:




// C++ program to illustrate the
// multiset::value_comp() function
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // Creating a multiset named m;
    multiset<int> m;
  
    multiset<int>::value_compare
        comp
        = m.value_comp();
  
    // Inserting elements into multiset
    m.insert(10);
    m.insert(20);
    m.insert(30);
    m.insert(40);
  
    cout << "Multiset has the elements\n";
  
    // Store key value of last element
    int highest = *m.rbegin();
  
    // initializing the iterator
    multiset<int>::iterator it = m.begin();
  
    // printing elements of all multiset
    do {
  
        cout << " " << *it;
  
    } while (comp(*it++, highest));
  
    return 0;
}
Output:
Multiset has the elements
 10 20 30 40

Example 2:




// C++ program to illustrate the
// multiset::value_comp() function
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // Creating a multiset named m;
    multiset<int> m;
  
    multiset<int>::value_compare
        comp
        = m.value_comp();
  
    // Inserting elements into multiset
    m.insert(100);
    m.insert(200);
    m.insert(300);
    m.insert(400);
  
    cout << "Multiset has the elements\n";
  
    // Store key value of last element
    int highest = *m.rbegin();
  
    // initializing the iterator
    multiset<int>::iterator it = m.begin();
  
    // printing elements of all multiset
    do {
  
        cout << " " << *it;
  
    } while (comp(*it++, highest));
  
    return 0;
}
Output:
Multiset has the elements
 100 200 300 400
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :