Implement a MultiKeyMap in C++
This post will discuss how to implement a MultiKeyMap (map with multiple keys) in C++.
A MultiKeyMap is a map that offers support for multiple keys. It is exactly the same as a normal map, except that it needs a container to store multiple keys. A simple solution to implement a MultiKeyMap in C++ is using std::pair for the key. To insert elements into the multimap, use the [] operator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <map> int main() { std::map<std::pair<int,int>, int> multimap; std::pair<int,int> key = std::make_pair(1, 2); int val = 10; multimap[key] = val; std::cout << multimap[key] << std::endl; // 10 return 0; } |
If a key exists in the map, the [] operator will override the original value with the new value. To retain the original value in such cases, consider using the std::map::insert function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <map> int main() { std::map<std::pair<int,int>, int> multimap; std::pair<int,int> key = std::make_pair(1, 2); int val = 10; multimap.insert({key, val}); std::cout << multimap[key] << std::endl; // 10 return 0; } |
This works fine for a multimap having two keys of the same or different types. To construct a multimap with three keys of the same or different types, we can use std::tuple instead.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> #include <tuple> int main() { std::map<std::tuple<int,int,int>, int> multimap; std::tuple<int,int,int> key(1, 2, 3); int val = 10; multimap[key] = val; std::cout << multimap[key] << std::endl; // 10 return 0; } |
To create a multimap with an arbitrary number of keys of the same type, use the std::vector instead. This can be implemented as follows in C++.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> #include <vector> int main() { std::map<std::vector<int>, int> multimap; std::vector<int> key = {1, 2, 3}; int val = 10; multimap[key] = val; std::cout << multimap[key] << std::endl; // 10 return 0; } |
Also See:
That’s all about implementing a MultiKeyMap in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)