Implement Dictionary using Multimap in C++
Hello Folks!!!
Welcome to this tutorial in which you are going to learn how to implement a Dictionary using multimap in C++.
- Dictionary is a built-in data type in Python that stores data in the key-value pair. So here in this tutorial, we will write a C++ program that will work similarly to the Dictionary in Python.
Problem:
Implement a dictionary using multimap by storing a few words having multiple meanings. For eg., “Apple” is both a fruit and the name of a company, “Kiwi” is both a fruit and a bird.
Example:
Apple: A fruit Apple: A company Kiwi: A fruit Kiwi: A bird.
Approach:
- Although, using Multimap is not the best way of implementing a dictionary as it can be more optimized by using the Trie data structure, but we have used this to explain one of the many uses of a multimap.
- To do this, just create a multimap and store in it a key and its multiple values. There is a single key that can have more than one value.
- The insert function can be used to insert multiple pairs of values into a multimap having the same key but different values.
- Then this multimap can be displayed using the begin and end operation implemented through a for loop.
Program:
// C++ code illustrating how to // implement dictionary using a multimap #include <bits/stdc++.h> using namespace std; // Main function int main(void) { // Declaring a multimap multimap<string, string> D; // Inserting key_value pair1 D.insert( pair<string, string> ("Kiwi", "A fruit") ); // Inserting key_value pair2 D.insert( pair<string, string> ("Kiwi", "A Bird") ); // Displaying the contents of multimap for (auto it = D.begin(); it != D.end(); it++) cout << it->first << " : " << it->second << " " <<"\n"; return 0; }
If you try to run the above program then you will get the output as,
Kiwi : A fruit Kiwi : A Bird
So that’s all for this tutorial. I hope you have understood the concept thoroughly.
Thank you for going through this tutorial.
Comment down for any queries.
Leave a Reply