C++ multiset - key_comp() Function
The C++ multiset::key_comp function returns a copy of the comparison object used by the container. By default, it is a less object, which returns the same as operator<.
Syntax
key_compare key_comp() const;
key_compare key_comp() const;
Parameters
No parameter is required.
Return Value
The comparison object associated to the container.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the multiset::key_comp function is used print all elements in the given multiset which are less than 50.
#include <iostream> #include <set> using namespace std; int main (){ multiset<int> MSet{10, 20, 20, 30, 30, 40, 70, 80, 90}; multiset<int>::iterator it; //printing the content of the multiset cout<<"MSet contains:"; for(it = MSet.begin(); it != MSet.end(); ++it) cout<<" "<<*it; //creating a key_comp object multiset<int>::key_compare MyComp = MSet.key_comp(); //printing all elements in multiset which are //less than 50 using key_comp object it = MSet.begin(); cout<<"\nElements less than 50 in MSet:\n"; while(MyComp(*it, 50)){ cout<<*it<<" "; it++; } return 0; }
The output of the above code will be:
MSet contains: 10 20 20 30 30 40 70 80 90 Elements less than 50 in MSet: 10 20 20 30 30 40
❮ C++ <set> Library