Dictionary in C++ with examples

Dictionary is a collection of key, value pairs. They can be changed. Let’s understand it with an example suppose you own a bakery there is a price corresponding to each cake. So here keys are cake names (i.e. vanilla, chocolate…), and their prices are the corresponding values.

In C++, A dictionary can be implemented with the help of  Map in standard template libraries (STL).

Map in STL

A map stores key-value pairs. Remember that Maps always sort these key-value pairs by the key elements.

The syntax for map declaration is:-

map <data_type_of_key, data_type_of_value> variable_name;

How to create a Dictionary in C++ ?

The creation of a dictionary is very easy in C++. I will show you how to do it in very simple steps.

  1. Inclusion of header File: The first step is to include the header file map. In our case, we also use strings to store the names that act as keys so we will also include the header file string.

 

#include<map>
#include<string>

2. Creation of Map:- Now let’s create a map in which the key is a string ( cake names) and the values are floats (Prices), and we’ll name it as a bakery.

 

map<string, float>  bakery;

3. Assigning values:- Now we will assign values to our respective keys by using the index method.

 

bakery["Choclatecake"] = 585.5;
bakery["Strawberrycake"] = 579;
bakery["Mangocake"] = 345.6;
bakery["Vanillacake"] = 650;
bakery["MixedFruitcake"] = 539.9;

4. Using Loop:-  Here we will Loop through the map elements using two map methods i.e. begin() to point at the beginning of the map, and end() to point next to the last element of the map. Also, iter is the iterator in our case.

You might be wondering what’s the role of *. let me make it clear to you, we use the (dereference operator * ) to fetch that element where the pointer is pointing.

Also in our case .first accesses the first value of a pair (i.e. key) and .second accesses the second value of the pair (i.e. value).

map <string,float> :: iterator iter;
cout<<"keys"<<"  &  "<<"value"<<endl;
for (iter = bakery.begin(); iter != bakery.end(); iter++)
 {
   cout<<(*iter).first<<"    "<<(*iter).second<<"\n";
 }

Entire code

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

using namespace std;

int main(){

   
   map<string, float> bakery;
   bakery["Choclatecake"] = 585.5;
   bakery["Strawberrycake"] = 579;
   bakery["Mangocake"] = 345.6;
   bakery["Vanillacake"] = 650;
   bakery["MixedFruitcake"] = 539.9;

    map <string,float> :: iterator iter;

   cout<<"keys"<<"  &  "<<"values"<<endl;

   for (iter = bakery.begin(); iter != bakery.end(); iter++)
   {
     cout<<(*iter).first<<"    "<<(*iter).second<<"\n";
   }


    return 0;

Output:-

keys & values
Choclatecake 585.5
Mangocake 345.6
MixedFruitcake 539.9
Strawberrycake 579
Vanillacake 650

Leave a Reply

Your email address will not be published.