What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Dictionary in C++: Method to Create Dictionaries with Example

  • Nov 09, 2023
  • 5 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Manvi Saxena
Dictionary in C++: Method to Create Dictionaries with Example

You must have heard about Python Dictionary, but have you ever wondered how we can create and use a Dictionary in C++. In this article, we will discuss the concept of dictionaries in C++, their implementation using the Map object in the Standard Template Library (STL), and step-by-step instructions on how to create a dictionary in C++. We will also check out some examples to help us understand the topic better.

What is a C++ Dictionary?

Maps in C++ actually work just like a Dictionary when the datatype of all elements in it is the same. A map is a container in C++ that stores key-value pairs which are indexed with the help of keys. Each value in a particular container is associated with a unique key. The maps always sort these key-value pairs based on the keys. We can use different ways to Iterate through Map in C++ like STL iterators or range based for loop.

It should be taken care of that all keys in a C++ map should be of the same data type. However, it is not necessary that both keys and values are of the same type. To use maps in C++, a header file specified for maps should be included in the standard library.

Syntax of Dictionary in C++

Here is the syntax for using Dictionary:

map<datatype_of_key, datatype_of_value> name_of_map;

 

Let's breakdown this syntax:

  • map: map is the data type representing the map container in C++. It is part of the C++ Standard Template Library (STL). You need to include the  header to use it.

  • <datatype_of_key, datatype_of_value>: Inside angle brackets < >, you specify two data types:
    • datatype_of_key: This is the data type for the keys in the map. Keys are used to index and access values in the map. For example, it can be an int, string, or any other data type depending on the specific use case.
    • datatype_of_value: This is the data type for the values associated with each key in the map. Values are the data you want to store or retrieve using the keys. It can also be any valid data type, such as double, string, or a custom data structure.

  • name_of_map: This is the name you give to the particular instance of the map you are declaring. This name is used to reference the map in your code.

Working on Dictionary in C++

Dictionaries in C++ work in accordance with the following points:

  • The Dictionary type present in C++ language is called a Map that acts like a container that stores values indexed by unique keys.
  • Each value in the dictionary is associated with a unique key.
  • The data type of all values should be the same and of keys should be the same.
  • To use this feature of C++, a specified header file should be included in the C++ Standard Library. 
  • Using a loop, the values in the map can be iterated where each iterated item represents a pair of keys and values. 

Creating a Dictionary in C++

We have listed the following steps for creating a C++ Dictionary. Follow them to create one of your own:

1. Including Header File

Before beginning or initializing any variable, the first and foremost thing to do is to include the header file for creating the dictionary. If you are going to use strings for names or something like that, make sure to include that file as well. 

#include<map>
#include<string>

 

2. Creating a Map

Now that you have added the header file, it's time to create the map. We'll create a map where the key is a string(Student Names) and values are integers(their Roll Numbers). We'll name it as Section. 

map<string, integer> section;

 

3. Assigning Values

Thereafter, it's time to assign the values in our Dictionary. Look at the below code snippet:

section["Ananya"]=101;
section["Bhavya"]=102;
section["Dev"]=103;
section["Jay"]=104;
section["Om"]=105;

 

4. Traversing via Loop

Now that you have given entries as well, let's move forward to iterate through the elements. Two methods are used for traversing begin() which points to the beginning of the map and end() which points to the last element of the map. 

In the below code snippet, .first accesses the first value of a pair, and .second accesses the second one. 

map <string,integer> :: iterator i;
cout<<"Keys"<<"  &  "<<"Value"<<endl;
for (i = section.begin(); i!= section.end(); i++)
{
   cout<<(*i).first<<"    "<<(*i).second<<"\n";
}

 

5. Removing Elements from the Dictionary

If we want to remove an element from the dictionary, we can use the erase() function. Here's an example:

section.erase("Ananya")

 

6. Checking the Size of the Dictionary

To check the size of the dictionary (i.e., the number of elements), we can use the size() function:

cout << "The size of the dictionary is: " << section.size();

 

7. Clearing the Dictionary

If you want to remove all elements from the dictionary, you can use the clear() function. Here's an example:

section.clear();

 

Example of C++ Dictionary

Here is an example for you to try:

#include<iostream> 
#include<map>
#include<string> 

using namespace std;

int main() {
    map<string, string>CapitalCity;

    //Adding the elements
    CapitalCity["New Delhi"] = "India";
    CapitalCity["Bangalore"] = "Karnataka";
    CapitalCity["Mumbai"] = "Maharashtra";

    //Traversing through the map elements
    for (auto element :CapitalCity){

        //element.first represents key
        cout<<element.first<<" is the capital of ";

        //element.second represents value
        cout<<element.second<<endl;
    }

    // Removing an element
    CapitalCity.erase("Mumbai");

    // Size of Map
    cout<<"The size of Map is :"<< CapitalCity.size();

    // Clear the Map
    CapitalCity.clear();
return 0;
}

 

Output:

New Delhi is the capital of India. 
Bangalore is the capital of Karnataka. 
Mumbai is the capital of Maharashtra.
The size of Map is :2

 

In the above C++ program, we have used a map called CapitalCity to store capital cities and their corresponding countries or states. We added the key-value pairs to the map and then traversed the map elements to print each city and its associated country/state. The output displays the capital cities and their respective locations.

Important Points to Remember

These are some important points about C++ Dictionary:

  • The Map object in C++ ensures that the key-value pairs are sorted based on the keys, allowing for efficient searching and retrieval.
  • Dictionaries in C++ are particularly useful when you need to associate data with specific keys and perform operations based on those associations.
  • You can use any data type as the key and value in a dictionary, as long as they are compatible with the map declaration.
  • Remember to include the necessary header files and use the appropriate syntax when working with dictionaries in C++.

Conclusion

C++ dictionaries, implemented with the Map object, are a powerful tool to manage and manipulate data efficiently in your C++ applications. Understanding their syntax and usage can greatly enhance your programming capabilities and enable you to work with complex data structures effectively. With the step-by-step building of a dictionary in C++ and a whole new example, you must have gained a good amount of experience in this subject. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Manvi Saxena
I'm Manvi Saxena, a technophile, and technical content writer. Having a curious mind helps me gain exposure and explore the latest technologies. Being a coder myself, it feels fantastic to share my knowledge via tech blogs to help others.