Dictionary in C++

Dictionary in C++

A dictionary can be implemented in C++ with the help of std::map of standard template library (STL). It can implement sorted key-value pairs with unique keys. We can alter, search, remove and insert the values associated with the keys in a map within O(N) time complexity. But we can only insert or delete the keys, we cannot alter them.
In this article, we will discuss different ways to create a dictionary in C++ and basic functions which are associated with it.
[toc]

How to create a dictionary in C++?

We can initialize a dictionary using different methods. Let’s understand them:

In C++, the key-value pairs are separated by commas and curly brackets are used for initialization. Methods to create a dictionary are given below:

Code:

#include 
#include 
#include 
using namespace std;

int main() {

    //METHOD 1: Using Initializer List
    map language = {{1, "Java",},
                                {2, "Python",},
                                {3, "C++",},
                                {4, "Javascript"},
                                };

    map::iterator itr;

    //Printing the map: language
    cout << "The map language is : \n";
    cout << "\tKEY\tELEMENT\n";
    for (itr = language.begin(); itr != language.end(); ++itr) {
        cout << '\t' << itr->first
            << '\t' << itr->second << '\n';
    }
    cout << endl;

    //METHOD 2: Using default constructor
    map fruits;
        fruits[1] = "Banana";
        fruits[2] = "Mango";
        fruits[3] = "Cocoa";
        fruits[4] = "Raspberry";

    //Printing the map: fruits
    cout << "The map fruits is : \n";
    cout << "\tKEY\tELEMENT\n";
    for (itr = fruits.begin(); itr != fruits.end(); ++itr) {
        cout << '\t' << itr->first
            << '\t' << itr->second << '\n';
    }
    cout << endl;

    //METHOD 3: Using Insert() function and Pair
    map cars;
    cars.insert(pair(1, "Honda"));
    cars.insert(pair(2, "Toyota"));
    cars.insert(pair(3, "Maruti"));
    cars.insert(pair(4, "Mercedes"));

    //Printing the map: cars
    cout << "The map cars is : \n";
    cout << "\tKEY\tELEMENT\n";
    for (itr = cars.begin(); itr != cars.end(); ++itr) {
        cout << '\t' << itr->first
            << '\t' << itr->second << '\n';
    }
    cout << endl;

    //Method 4: New dictionary with copied values from different dictionary
    //Creating map2 with language map values

    map map2(language);

    //Printing the map: map2
    cout << "The map map2 is : \n";
    cout << "\tKEY\tELEMENT\n";
    for (itr = map2.begin(); itr != map2.end(); ++itr) {
        cout << '\t' << itr->first
            << '\t' << itr->second << '\n';
    }
    cout << endl;

    //Method 5: Creating new dictionary by copying key-value pairs in a specific range
    map map3(fruits.find(3), fruits.end());

    //Printing the map: map3
    cout << "The map map3 is : \n";
    cout << "\tKEY\tELEMENT\n";
    for (itr = map3.begin(); itr != map3.end(); ++itr) {
        cout << '\t' << itr->first
            << '\t' << itr->second << '\n';
    }
    cout << endl;

    return 0;
}

Output:

The map language is :
KEY ELEMENT
1 Java
2 Python
3 C++
4 Javascript

The map fruits is :
KEY ELEMENT
1 Banana
2 Mango
3 Cocoa
4 Raspberry

The map cars is :
KEY ELEMENT
1 Honda
2 Toyota
3 Maruti
4 Mercedes

The map map2 is :
KEY ELEMENT
1 Java
2 Python
3 C++
4 Javascript

The map map3 is :
KEY ELEMENT
3 Cocoa
4 Raspberry

Member functions associated with Map in C++:

Modifiers

  • clear(): It can be used to empty the map.
  • erase(): It will remove the element which is stored at the iterator position, or value at the given key, or in the range as well.
  • pair insert(key, value): It is used to add new elements in the map.
  • swap(map): Exchanges the elements of two containers.
  • emplace(): It will insert a new key-value pair in the map if there is no equivalent key present in the map before the execution of this function.

Code:

#include 
#include 
#include 
using namespace std;

template
void print(Map &m)
{
   cout << "[ ";
    for (auto &item : m) {
        cout << item.first << ":" << item.second << " ";
    }
    cout << "]\n";
}

int main() {

    map::iterator it1;
    map::iterator it2;
    map dictionary = {{1, "Java",},
                                {2, "Python",},
                                {3, "C++",},
                                {4, "Javascript",},
                                {5, "PHP",},
                                {6, "C#",},
                                {7, "Pascal",},
                                {8, "Spring",}};
   //ERASE FUNCTION
    it1=dictionary.begin();   
    dictionary.erase(it1);   //erasing by iterator

    dictionary.erase(2);    //erasing by key

    it1=dictionary.find(3);          
    it2=dictionary.find(5);
    dictionary.erase(it1,it2); //erasing by range
    cout<<"Map after erase:";
    print(dictionary);

    //INSERT FUNCTION
    dictionary.insert(pair(1, "Java"));
    dictionary.insert(pair(2, "Python"));
    dictionary.insert(pair(3, "C++"));
    dictionary.insert(pair(4, "Javascript"));
    dictionary.insert(pair(9, "SQL"));
    cout<<"\nMap after insert:";
    print(dictionary);

    //SWAP FUNCTION
    map map2;
    map2[1]="Honda";
    map2[2]="Mercedes";
    map2[3]="Audi";
    map2[4]="Toyota";
    dictionary.swap(map2);
    cout<<"\nMap2 conains:";
    print(map2);
    cout<<"\nDictionary contains:";
    print(dictionary);

    //EMPLACE FUNCTION
    dictionary.emplace(5,"Porsche");
    dictionary.emplace(6, "Rolls Royce");
    cout<<"\nAfter emplace:";
    print(dictionary);
  //CLEAR FUNCTION
    dictionary.clear();
    cout<<"\nAfter Clear:";
    print(dictionary);

    return 0;
}

Output:

Map after erase:[ 5:PHP 6:C# 7:Pascal 8:Spring ]

Map after insert:[ 1:Java 2:Python 3:C++ 4:Javascript 5:PHP 6:C# 7:Pascal 8:Spring 9:SQL ]

Map2 conains:[ 1:Java 2:Python 3:C++ 4:Javascript 5:PHP 6:C# 7:Pascal 8:Spring 9:SQL ]

Dictionary contains:[ 1:Honda 2:Mercedes 3:Audi 4:Toyota ]

After emplace:[ 1:Honda 2:Mercedes 3:Audi 4:Toyota 5:Porsche 6:Rolls Royce ]

After Clear:[ ]

Capacity

  • empty(): It will check if the map is empty
  • size(): It will return the number of key-value pairs in the map.
  • max_size(): It will return the maximum number of elements that the map can hold. Example: It can be used to check beforehand whether the map will allow for 1000 elements to be inserted.

Code:

#include 
#include 
using namespace std;

template
void print(Map &m)
{
   cout << "[ ";
    for (auto &item : m) {
        cout << item.first << ":" << item.second << " ";
    }
    cout << "]\n";
}

int main(){
    map dictionary = {{1, "Java",},
                                {2, "Python",},
                                {3, "C++",},
                                {4, "Javascript",},
                                };

    //Size fucntion                          
    cout<<"Size of dictionary(map) is:"<< dictionary.size();

    //max_size function
    cout<<"\nDictionary can hold: "<< dictionary.max_size()<<" values";
    if (dictionary.max_size()>1000){
        cout<<"\nThis map can hold more than 1000 values.";
    }
    else{
        cout<<"This map cannot hold 1000 values.";
    }

    //empty function
    if(dictionary.empty())
    {
    cout<<"\nDictionary is empty";
    }
    else
    {
        cout<<"\nDictionary is not empty";
    }

    return 0;
}

Output:

Size of dictionary(map) is:4
Dictionary can hold: 384307168202282325 values
This map can hold more than 1000 values.
Dictionary is not empty

Iterators

  • begin(): Returns an iterator to the first element in the map.
  • end(): Returns an iterator to the last element in the map.
  • rbegin() It will return a reverse iterator which will be pointing to the last element in the container. Reverse iterator iterates backwards.
  • rend(): It will return a reverse iterator which will point to the first element in the container.

Code:

#include 
#include 
#include 
using namespace std;

int main() {

    map::iterator it;
    map dictionary = {{1, "Java",},
                                {2, "Python",},
                                {3, "C++",},
                                {4, "Javascript",},
                               };

    //PRINTING dictionary USING BEGIN() & END() FUNCTION
    cout<<"USING BEGIN & END";
    cout << "\nElements in dictionary are : \n";
    cout << "\tKEY\tELEMENT\n";
    for(it=dictionary.begin();it!=dictionary.end(); it++)
    {
        cout << '\t' << it->first
            << '\t' << it->second << '\n';
    }

    //PRINTING USING RBEGIN() & REND()

    map::reverse_iterator itr;
    cout<<"USING RBEGIN & REND";
    cout << "\nElements in dictionary are : \n";
    cout << "\tKEY\tELEMENT\n";
    for(itr=dictionary.rbegin();itr!=dictionary.rend(); ++itr)
    {
        cout << '\t' << itr->first
            << '\t' << itr->second << '\n';
    }

    return 0;
}

Output:

USING BEGIN & END
Elements in dictionary are :
KEY ELEMENT
1 Java
2 Python
3 C++
4 Javascript
USING RBEGIN & REND
Elements in dictionary are :
KEY ELEMENT
4 Javascript
3 C++
2 Python
1 Java

Operations

  • find(k): It will search for the key x in the container and will return an iterator if found or it will take the iterator to the end.
  • count(x): It will search for the key x in the container and will return the number of matches.
  • lower_bound(): It returns an iterator pointing to the first element whose key is not considered to go before ‘x’(it will be either equivalent or greater)
  • upper _bound():It returns an iterator pointing to the element whose key is considered to go after ‘x’. It returns an iterator pointing to the next element where it finds the equivalent key.
  • equal_range(): It returns a pair of iterators. Pair means the bounds of a range which will include all the elements in the container which have a key equivalent to ‘x’. Maps only have unique keys, so the first iterator in the pair points to the next key that is after ‘x’.

Code:

#include 
#include 
#include 
using namespace std;

int main() {

    map::iterator it1,it2,it3;
    map dictionary = {{1, "Java",},
                                {2, "Python",},
                                {3, "C++",},
                                {4, "Javascript",},
                              };
    //USING FIND FUNCTION
    cout<<"Element 1 Value="<second;
    cout<<"\nElement 2 Value="<second<<"\n";

    //USING COUNT FUNCTION
    //Find out if the elements are present in the map or not
    for(int i=1; i<7;i++)
    {
        cout<0)
        {
            cout<<"is an element of dictionary.\n";
        }
        else
        {
            cout<<"is not an element of dictionary.\n";
        }
    }

    //USING LOWER BOUND AND UPPER BOUND
    it1=dictionary.lower_bound(2);  //points to key:2
    it2=dictionary.upper_bound(4);  //points to 5 (not 4)

    dictionary.erase(it1,it2);  //erases elements from it1 to it2
        //printing the dictionary
    for(it3=dictionary.begin();it3!=dictionary.end(); it3++)
    {
        cout<first <<"=" <second <<'\n';
    }

    //USING EQUAL_RANGE
        map dictionary2 = {{1, "Java",},
                                {2, "Python",},
                                {3, "C++",},
                                {4, "Javascript",},
                               };
    pair::iterator,map::iterator> it4;
    it4=dictionary2.equal_range(2);

    //printing
    cout<<"\nLower bound points to= ";
    cout<first <<" --> " <second ;

    cout<<"\nUpper bound points to= ";
    cout<first<<" --> "<second;

    return 0;
}

Output:

Element 1 Value=Java
Element 2 Value=Python
1 is an element of dictionary.
2 is an element of dictionary.
3 is an element of dictionary.
4 is an element of dictionary.
5 is not an element of dictionary.
6 is not an element of dictionary.
1=Java

Lower bound points to= 2 --> Python
Upper bound points to= 3 --> C++

Conclusion

In this article, we discussed methods to create a dictionary in C++ and its member functions which can be used to perform different types of operations.

That's all about Dictionary in C++.
Happy Learning!!

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.