Javatpoint Logo
Javatpoint Logo

multimap key_comp() in C++

In this article, you will learn about the multimap::key_comp() function in C++ with its syntax and example. But before discussing its implementation, you must know about the multimap in C++.

What is Multimap in C++ STL?

Associative containers, or multimaps, are comparable to map containers. Additionally, storing the components made up of mapped value and key-value pairs in a particular order makes it easier. It is possible for several elements in a multimap container to share a single key. The corresponding keys are always used to internally sort the data in a multimap.

What is multimap::key_comp()?

Multimap::key_comp () is part of the <map> header file. This function returns a duplicate of a key comparison object. By default, it is a less-than object that functions similarly as a less-than operator (<<). The multimap container's element keys are checked for order by the object. This function accepts two arguments, checks the keys, and returns true if the smaller of the two elements should come first; otherwise, it returns false.


It has the following syntax:


This function accepts no parameter.

Return value:

It returns a comparison object.


Let us take an example to illustrate the multimap::key_comp() function in C++.


multimap key_comp() in C++

Benefits of multimap key_comp():

A standard template library (STL) container in C++ that is comparable to std::map but supports multiple elements with the same key is called std::multimap. The comparison object is used to compare keys and is retrieved using the std::multimap key_comp() member function. Some advantages of std::multimap's key_comp() include the following:

  • Custom Sorting Criteria: You can use the key_comp() to get the comparison object and alter the sorting criteria for the keys in the multimap. It is especially helpful in situations where the built-in key comparison does not meet your needs.
  • Consistent Comparison: The key_comp() ensures that the internal comparison and the comparison made when the multimap was created are both consistent. Consistency is essential for the multimap's elements to remain in their proper order.
  • Algorithm Compatibility: Using the comparison object returned by key_comp(), you can consistently compare keys in different code sections in other algorithms or containers that call for a comparison object.
  • Correctness and Stability: The multimap's correctness and stability are preserved using the key_comp() Once elements are inserted into the multimap, changing the comparison criteria may cause unexpected behaviour and order.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA