C++ multimap - key_comp() Function
The C++ multimap::key_comp function returns a copy of the comparison object used by the container to compare keys. 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 multimap::key_comp function is used print all elements of the given multimap with key less than 'USA'.
#include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MMap; multimap<string, string>::iterator it; MMap.insert(pair<string, string>("USA", "New York")); MMap.insert(pair<string, string>("USA", "Washington")); MMap.insert(pair<string, string>("CAN", "Toronto")); MMap.insert(pair<string, string>("CAN", "Montreal")); MMap.insert(pair<string, string>("IND", "Delhi")); //printing the content of the multimap cout<<"MMap contains: \n "; for(it = MMap.begin(); it != MMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; //creating a key_comp object multimap<string, string>::key_compare MyComp = MMap.key_comp(); //printing all elements of the multimap which has //key than 'USA' using key_comp object it = MMap.begin(); cout<<"\nElements of MMap with key less than 104:\n "; while(MyComp((*it).first, "USA")){ cout<<it->first<<" "<<it->second<<"\n "; it++; } return 0; }
The output of the above code will be:
MMap contains: CAN Toronto CAN Montreal IND Delhi USA New York USA Washington Elements of MMap with key less than 104: CAN Toronto CAN Montreal IND Delhi
❮ C++ <map> Library