MultiKeyMap in C++

In this tutorial, we will learn about MultiKeyMap in C++. Hope you will enjoy learning from this tutorial and make use of the implementation in your programming skills.

MultiKeyMap in C++

Map in C++ refers to key-value pair, where each key is unique. Multimap keys are different from maps in nature. Multimap in C++ refers to associative containers that contain a sorted list of key-value pairs that allow multiple entries with the same keys. Multimap mapped values in a particular order, where we can see multiple elements can have equivalent keys. MultiMap offers support for multiple keys. We need to include the <map> header file.

A user-provided Compare can be supplied to change the ordering that is one can sort the map according to their need. Search, removal, and insertion takes logarithmic time. It is usually represented as RB trees.

       class Key,
       class T,
       class Compare = std::less<Key>,
       class Allocator = std::allocator<std::pair<const Key,T>>,
      >class multimap;

Suppose in multimap if we have 
key1 as 10 and its value as abc;
key2 as 10 and its value as xyz;
this is not supported in <map>.


Each element in the map is identified by its key value.


Each element in the multimap stores some data which is a mapped value.


Example 1:

#include <iostream>
#include <map>
using namespace std;
int main() {
   multimap<int, string> multimapexample = {{10,"dog"},{20,"cat"},{30,"rat"}};
   cout << "size = " << multimapexample.size() << endl;  // print size of multimap

   for(auto& p: multimapexample)
       cout<< "{" << p.first << "," << p.second << "}"; // iterating in multimap



size = 3
{10,dog} {20,cat} {30,rat}


#include <iostream>
#include <map>
#include <vector>
int main()
    std::map<std::vector<int>, int> multimaps;
    std::vector<int> key = {1, 2, 3}; // 
    int value = 10;
    multimap[key] = value;
    std::cout << multimaps[key] << std::endl;  
    return 0;
Output: 10

Hope you liked this tutorial !!!!!!!!!

Also Read: Multithreading in C++

Leave a Reply

Your email address will not be published.