
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Multimap Key Comparison in C++ STL
In this article we will be discussing the working, syntax, and examples of multimap::key_comp() function in C++ STL.
What is Multimap in C++ STL?
Multimaps are the associative containers, which are similar to map containers. It also facilitates to store the elements formed by a combination of key-value and mapped value in a specific order. In a multimap container there can be multiple elements associated with the same key. The data is internally always sorted with the help of its associated keys.
What is multimap::key_comp()?
The multimap::key_comp( ) is a function which comes under <map> header file. This function returns a copy of a key comparison object. This is by default a less than an object which works the same as a less than operator <. The object checks the order of the element keys in the multimap container. This function takes the two arguments and checks its keys and returns true if the first element is smaller and should go before the second element, else will return false.
Syntax
Key_compare.key_comp();
Parameters
This function accepts no parameter.
Return value
It returns a comparison object.
Input
multimap<char, int> newmap; multimap<char, int> :: key_compare cmp = newmap.key_comp(); newmap.insert(make_pair(‘A’, 1)); newmap.insert(make_pair(‘B’, 2)); newmap.insert(make_pair(‘C’, 3));
Output
A= 1 B= 2 C= 3
Example
#include <iostream> #include <map< using namespace stgd; int main(){ multimap<int, char> mul; multimap<int, char>::key_compare cmp = mul.key_comp(); //inserting elements at given key mul.insert(make_pair(0, 'A')); mul.insert(make_pair(1, 'B')); mul.insert(make_pair(2, 'C')); mul.insert(make_pair(3, 'D')); int a = mul.rbegin()->first; multimap<int, char>::iterator it = mul.begin(); cout<<"Elements at given key is : "<<'\n'; do { cout << it->first << " = " << it->second << '\n'; } while (cmp((*it++).first, a)); return 0; }
Output
If we run the above code it will generate the following output −
Elements at given key is : 0 = A 1 = B 2 = C 3 = D