C++ Dictionary: Using map and unordered_map (With Code)

How To Create C++ Dictionary

In Python, you might have worked with a dictionary, and while learning C++, you want to utilize the same. But here is the secret. You will not find any C++ Dictionary concept as it is not valid in C++.

However, the implementation of a dictionary-like data structure can be possible in C++ with the help of the std::map container. In academic assignments and competitive programming problems, C++ dictionaries are commonly used for frequency counting and fast lookups.

The short answer: to make a dictionary in C++, include the <map> header, declare a map with the type of the key and the type of the value, and add pairs with square brackets.

map<string, int> age;      // key is a string, value is an int
age["Tom"] = 20;           // add a pair
cout << age.at("Tom");     // prints 20

In this article, we are going to define the dictionary in C++ in a very simple manner. Every program on this page was compiled with g++ and run before we put it here, and the output under each one is copied from that run. Let's begin our discussion.

TL; DR: C++ Dictionary

AspectSummary
Dictionary ConceptC++ does not have a built-in dictionary; map and unordered_map store key-value pairs like a dictionary.
Types of MapsMap keeps keys sorted; unordered_map uses hashing and does not maintain order, offering faster access.
Adding & Accessing ElementsUse map[key] = value; to add elements; loops with .first and .second access keys and values.
Missing KeysReading a missing key with [] quietly creates it. Use find(), count(), or at() when you only want to check or read.
Copying DictionariesNew dictionaries can be created from existing ones by copying the original map object.
Common Mistakes & ComparisonAvoid missing headers, wrong data types, or incorrect use of .first and .second; C++ maps are statically typed, so every key has one type and every value has one type.

What Is A C++ Dictionary? Get To Know

You might be thinking that C++ Dictionary will help to find words like a normal dictionary. But you are wrong here. So, let us start with the introduction!

C++ Dictionary

It is a container where a programmer can store many elements. Now, you might ask in the array, we can store the data, so what is the necessity of the C++ Dictionary? Now, can you find any element with a particular value in the array?

You can use the index number, but for that, there is a need to know the particular index number. In the case of a dictionary in the C++ programming language, you do not need any index number. You find each value by a name that you choose yourself, like "Tom" or "Books". Also, these names can be used for printing purposes.

This means that values in a dictionary are associated with unique keys that can be used to access them. We call these key value pairs. A normal word dictionary is a good way to remember it. The word you look up is the key, and its meaning is the value.

In the C++ programming language, there is no Dictionary concept present.

Why C++ Does Not Have A Built-in Dictionary Like Python?

C++ does not provide a built-in data structure called a Dictionary like Python because C++ is designed as a low-level and performance-oriented language. C++ gives programmers more control over how data is stored and accessed.

To access dictionary-like behavior in C++, we have to use different containers like std::map and std::unordered_map in the Standard Template Library (STL).

These containers store data in key-value pairs, just like a Python dictionary. It also allows developers to choose between sorted storage and faster access, depending on the problem requirement.

Python Dictionary To C++: A Quick Cheat Sheet

If you are coming from Python, this table will save you a lot of time. On the left is what you write in Python, and on the right is how the same thing is done in C++. Each line on the right is explained with a full program later in this article.

TaskPythonC++ (map or unordered_map)
Create an empty dictionaryd = {}map<string, int> d;
Create with datad = {"Tom": 20}map<string, int> d = {{"Tom", 20}};
Add or change a paird["Tom"] = 20d["Tom"] = 20;
Read a valued["Tom"]d.at("Tom") (or d["Tom"], but read this first)
Read with a defaultd.get("Tom", 0)No direct match. Use find()
Check if a key exists"Tom" in dd.count("Tom") or d.contains("Tom") in C++20
Remove a keydel d["Tom"]d.erase("Tom"); (no error if the key is missing)
Number of pairslen(d)d.size()
Loop over pairsfor k, v in d.items():for (auto item : d) with item.first and item.second (a map gives sorted order)
Remove everythingd.clear()d.clear();

Now, let us understand how we can create a dictionary in the C++ programming language and the concept of object mapping.

How To Create The C++ Dictionary?

Now, after having a piece of good knowledge about the Dictionary in C++ programming language, there is a need to implement it, and for that, we need to follow some steps. That is the reason we have made the total process in a step-by-step format.

Create C++ Dictionary

Let’s get started with the first step of declaring the header files we require in our program.

Declaration Of The Header File:

For using the Map concept in C++ programming, there is a need to declare a special header file.

As the Map is the Dictionary in C++ programming language, we need to import the #include <map> header file to the programming.

#include <iostream> // Declaration Of The Normal Header File
#include <map> // The Necessary Important Header File For Dictionary
#include <string> // Needed When The Keys Or Values Are Strings

Declaration Of The Map:

After we declare the header file in the programming, there is a need to declare the map, too. A Map is a container that stores the key-value pairs in C++ language. To create a dictionary using a C++ map of the Standard Template Library or STL, we need to first declare it.

We need to first write the word ‘map’ for declaration. Then we are going to provide the data types of the Key & the Value to form the key-value pairs in it. At last, there is a need to provide the name of the Map object in the C++ programming language. Look at the syntax given below.

General Syntax: map<Key Data Type, Value Data Type> Map-Name;

The data type of the key always comes first, and the data type of the value comes second. For example, map<string, int> age; is a dictionary where every key is a string and every value is an int.

Map stores data in sorted order, which is useful when assignments require output in ascending key order.

Providing Keys & Values:

Now, it is time to map elements to create our dictionary. Let us see how we can do it.

After the declaration of the Map in C++ programming language, there is a need to provide the keys & values to make the key value pairs in it. To provide the values, there is a need to follow a special method. The key should be placed in the square brackets, and the value should be placed after the equal sign.

storage["Books"] = "Shelf"; // Books Is The Key & Shelf Is The Value

storage["Foods & Drinks"] = "Fridge"; // Foods & Drinks Is The Key & Fridge Is The Value

storage["Clothes"] = "Wardrobe"; // Clothes Is The Key & Wardrobe Is The Value

So, this is how you can map keys and values. You can access the value by using its key.

Implementation Of Loop:

After doing all these things, there is a need to develop a loop. Among them, there is a need to implement the for each loop. Because there is a need to access all the elements that are present in the Map in the C++ programming language.

To access these data, there is a need to use the Dot(.) operator. After the name of the loop variable, we need to use two special names to access it.

The first one will be ‘first’, which will help to access the keys that are inserted into the Map in the C++ programming language. And the other one will be ‘second’, which will help to access the values.

for (auto element : storage) { // Running A For Loop To Get All The Elements
    cout << element.first << " Can Be Stored In " << element.second << endl;
}

One small tip. Writing auto element makes a copy of each pair. For the small examples in this article, it makes no difference. With large values, write const auto& element to avoid the copy.

There are several other ways to loop over a map, like iterators and reverse loops. We have discussed all of them in our guide on how to iterate a map in C++.

Let us try to find out an entire code where all the above code snippets will collaborate to make a complete example. Let us have a look at the following example.

How To Implement A Complete C++ Dictionary?

Now, let us have a look at the example program below to see how we can create and access the elements or the key-value pairs of a user-defined dictionary using the C++ map.

Generally, we need to use std::map, wherever we are using the map. However, to eliminate the need to write this, we can simply use a namespace for the same i.e ‘using namespace std’. You can see how it is used in the below code.

#include <iostream> // Declaration Of The Header File
#include <map> // The Necessary Important Header File For Dictionary
#include <string>
using namespace std;

int main() {
    map<string, string> storage; // Declaration Of Dictionary or The Map

    // Assigning Elements To Dictionary, The Key Is In The Square Brackets & The Value Is After The = Sign
    storage["Books"] = "Shelf";
    storage["Foods & Drinks"] = "Fridge";
    storage["Clothes"] = "Wardrobe";

    for (auto element : storage) { // Running A For Loop To Get All The Elements
        cout << element.first << " Can Be Stored In " << element.second << endl; // Printing Each & Every Element
    }
    return 0;
}

Let us try to find out the output of the above code. It will help to make us understand the process of implementing Dictionary in C++ programming language.

Output:

Books Can Be Stored In Shelf
Clothes Can Be Stored In Wardrobe
Foods & Drinks Can Be Stored In Fridge

From the above output, we can see that the keys & the values are shown properly. So, the Dictionary of the C++ programming language works properly in the example.

Look at the order of the output as well. We inserted "Foods & Drinks" second, but it is printed last. The map has arranged the keys in alphabetical order on its own.

If we already know the data, there is no need to add the pairs one by one. We can give all of them inside braces at the time of declaration.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    // Creating The Dictionary With All Its Data In One Statement
    map<string, int> price = {{"Pen", 2}, {"Notebook", 5}, {"Backpack", 30}};

    cout << "Total Items: " << price.size() << endl;
    for (auto item : price) {
        cout << item.first << " Costs $" << item.second << endl;
    }
    return 0;
}

Output:

Total Items: 3
Backpack Costs $30
Notebook Costs $5
Pen Costs $2

Now, in the above step-by-step implementation process, we have discussed the creation method of one empty Dictionary in the C++ programming language. But we intend to know all the methods that lead to the creation of the Dictionary.

So, a Dictionary can also be created by using another Dictionary. We are going to know about that.

How To Create A Dictionary From Another Dictionary In C++?

It is the simplest process to implement. From one already existing Map or Dictionary, one can create another Dictionary & store the object. For that purpose, there is a special syntax present.

According to the syntax, the new Dictionary name should be provided first. Following that, the existing Dictionary from which the details should be copied needs to be placed inside the parentheses. And hence, without any issue, the details will be copied.

Let’s see how it will look based on the syntax in C++.

General Syntax: map<first data type, second data type> new-map-name(existing-map-name);

Code To Implement A C++ Dictionary From Another Dictionary:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> first = {{"Jerry", 10}, {"Tom", 20}}; // Implementation Of First Map
    map<string, int> two(first); // Copying All The Items To Another Dictionary

    two["Jerry"] = 11; // Changing The Copy Only

    for (auto a = two.begin(); a != two.end(); ++a) { // Implementation Of For Loop
        cout << a->first << " Is " << a->second << " Years Old" << endl; // Printing The Data
    }
    cout << "In The First Dictionary, Jerry Is Still " << first.at("Jerry") << endl;
    return 0;
}

Steps Of The Program To Implement a C++ Dictionary From Another Dictionary:

  • First, implement one Dictionary & provide some value to it. It will be used to copy data.
  • Now, using the above syntax, copy the content of the first Dictionary to the second Dictionary.
  • We change one value in the second Dictionary to check whether the two are really separate.
  • Implement one for loop & using that extract all the keys & values of the Dictionary. It will be printed on the screen.

Let us try to find out the output of the above code. It will help us understand the process of implementing a Dictionary in the C++ programming language.

Output:

Jerry Is 11 Years Old
Tom Is 20 Years Old
In The First Dictionary, Jerry Is Still 10

The last line of the output is important. We changed Jerry's age in the copy, but the first Dictionary still has the old value. In C++, copying a map makes a full, separate copy. Writing two = first; on an existing map does the same. This is different from Python, where two = first only gives a second name to the same dictionary.

How To Read A Value From A C++ Dictionary: [] vs at() vs find()

There are three ways to read a value, and they behave very differently when the key is not present. This is the place where C++ and Python behave most differently. In Python, reading a missing key gives a KeyError. In C++, the square brackets do something else. Let us have a look at the following program.

#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
using namespace std;

int main() {
    map<string, int> age = {{"Tom", 20}, {"Jerry", 18}};

    // 1. Square Brackets: Short, But Creates The Key If It Is Missing
    cout << "Tom Is " << age["Tom"] << endl;
    cout << "Spike Is " << age["Spike"] << endl;
    cout << "Size After Using []: " << age.size() << endl;

    // 2. at(): Never Creates A Key, Throws An Error Instead
    try {
        int butch = age.at("Butch");
        cout << "Butch Is " << butch << endl;
    } catch (const out_of_range&) {
        cout << "at() Says: Butch Is Not In The Dictionary" << endl;
    }

    // 3. find(): Never Creates A Key, Never Throws
    auto it = age.find("Jerry");
    if (it != age.end())
        cout << "find() Says: Jerry Is " << it->second << endl;

    cout << "Final Size: " << age.size() << endl;
    return 0;
}

Output:

Tom Is 20
Spike Is 0
Size After Using []: 3
at() Says: Butch Is Not In The Dictionary
find() Says: Jerry Is 18
Final Size: 3

Steps Of The Program:

  • We read "Tom" with the square brackets, and it works as expected.
  • Then we read "Spike", who was never added. There is no error. The map creates "Spike" with the value 0 and returns that 0. The size grows from 2 to 3.
  • The at() function refuses to create anything. For a missing key, it throws an out_of_range exception, which we catch.
  • The find() function returns an iterator. If the key is missing, the iterator is equal to end(), so we can check it with a simple if statement.

If we do not catch the exception from at(), the program stops. We ran it without the try-catch block, and this is what was printed:

terminate called after throwing an instance of 'std::out_of_range'
  what():  map::at

So, the rule is simple. Use the square brackets when you want to add or change a pair. Use at() or find() when you only want to read.

Python has the handy d.get(key, default) for this. C++ has no direct match, but we can write it ourselves in a few lines with the help of find().

#include <iostream>
#include <map>
#include <string>
using namespace std;

// Works Like Python's dict.get(key, default)
int getOr(const map<string, int>& dict, const string& key, int fallback) {
    auto it = dict.find(key);
    if (it != dict.end())
        return it->second;
    return fallback;
}

int main() {
    map<string, int> age = {{"Tom", 20}, {"Jerry", 18}};

    cout << getOr(age, "Tom", -1) << endl;
    cout << getOr(age, "Spike", -1) << endl;
    cout << "Size: " << age.size() << endl; // Nothing Was Added
    return 0;
}

Output:

20
-1
Size: 2

Notice that the function receives the Dictionary as const map&. On a const map, the square brackets do not even compile, because they might have to add a key. So, at() and find() are the only choices there.

How To Check If A Key Exists In A C++ Dictionary?

In Python, we write "Tom" in d. In C++, there is a need to use the count() function or the find() function. Both of them only look. They never add anything to the Dictionary.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> age = {{"Tom", 20}, {"Jerry", 18}};

    // count() Gives 1 If The Key Is Present And 0 If It Is Not
    if (age.count("Tom"))
        cout << "Tom Is In The Dictionary" << endl;

    if (age.count("Spike") == 0)
        cout << "Spike Is Not In The Dictionary" << endl;

    // find() Does The Check And Gives Us The Value In One Step
    auto it = age.find("Jerry");
    if (it != age.end())
        cout << "Jerry Is In The Dictionary With Value " << it->second << endl;

    cout << "Size: " << age.size() << endl; // Still 2, Nothing Was Added
    return 0;
}

Output:

Tom Is In The Dictionary
Spike Is Not In The Dictionary
Jerry Is In The Dictionary With Value 18
Size: 2

If your compiler supports C++20, there is a shorter and more readable way. The contains() function returns true or false directly. With g++, compile the following program using the -std=c++20 flag.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> age = {{"Tom", 20}, {"Jerry", 18}};

    if (age.contains("Tom")) // C++20 Only
        cout << "Tom Is In The Dictionary" << endl;
    if (!age.contains("Spike"))
        cout << "Spike Is Not In The Dictionary" << endl;
    return 0;
}

Output:

Tom Is In The Dictionary
Spike Is Not In The Dictionary

How To Update A Value In A C++ Dictionary?

To change a value, we can assign to the same key again with the square brackets. But there is one more function, insert(), and it does not behave the same way. Students often mix up these two.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> age = {{"Tom", 20}};

    age["Tom"] = 21; // Square Brackets Overwrite The Old Value
    cout << "After []: " << age["Tom"] << endl;

    age.insert({"Tom", 99}); // insert() Does Nothing If The Key Is Already There
    cout << "After insert(): " << age["Tom"] << endl;

    age.insert({"Jerry", 18}); // insert() Adds The Pair If The Key Is New
    age["Tom"] += 1; // The Value Can Be Changed Like A Normal Variable
    age["Tom"]++;

    for (auto item : age)
        cout << item.first << " : " << item.second << endl;
    return 0;
}

Output:

After []: 21
After insert(): 21
Jerry : 18
Tom : 23

From the above output, we can see that the square brackets changed Tom's age to 21. But the insert() call with 99 did nothing, because the key "Tom" was already there. The insert() function only adds new keys. It never overwrites.

The last lines show that a value in a Dictionary can be used like a normal variable. We can use += and ++ on it directly.

How Can Students Create A Dictionary Using Unordered_Map In C++?

Not only can students use the Map, but they can also create a dictionary in C++ with the help of the Unordered_Map. Unlike the Map, here, the keys are not stored in a sorted order. Instead, it uses a hash table to store them.

Oftentimes, we have seen in assignments that it has been particularly instructed that the students create a C++ dictionary using Unordered_Map. That is why going through the following code becomes essential.

Since unordered_map does not maintain order, it should not be used when sorted output is required.

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

int main() 
{
    unordered_map<string, int> scores; // The Dictionary With Unordered
    // Key Value Pairs
    scores["Newton"] = 85;
    scores["Tom"] = 90;
    scores["Spike"] = 78;

    for (auto item : scores) // Printing The Data
        cout << item.first << " Scored: " << item.second << endl;

    return 0;
}

The Unordered_Map will create a dictionary where the Key is a student's name and the value is the score. Here, the data is stored using hashing, so you can see that the output order may vary.

The First represents the key, and the Second represents the value. The loop is used to print all key and value pairs.

Output (on our machine):

Spike Scored: 78
Tom Scored: 90
Newton Scored: 85

We inserted Newton, Tom, and Spike in that order, but the output is neither in that order nor in alphabetical order. On your computer, it may come out in a different order again. Everything else we have discussed in this article, like at(), find(), count(), and erase(), works with the Unordered_Map in exactly the same way.

Time Complexity of C++ Dictionary Operations:

When working with a C++ dictionary, understanding time complexity is important because it directly affects the performance of your program. This topic is also frequently asked in data structures exams and interviews.

Time Complexity Using Map:

The map container in C++ stores data in sorted order using a balanced binary tree.

  • Searching for an element takes O(log n) time
  • Inserting a new key-value pair takes O(log n) time
  • Deleting an element also takes O(log n) time

Since the keys are always sorted, a map is useful when ordered output is required, but it is slower compared to hashing-based containers.

Time Complexity Using Unordered_Map:

The unordered_map container uses a hash table to store data, which allows much faster access.

  • Searching for an element takes O(1) time on average
  • Inserting a key-value pair takes O(1) time on average
  • Deleting an element takes O(1) time on average

In rare cases, when many keys map to the same hash location, the time complexity can become O(n). However, for most practical and academic problems, unordered_map performs much faster than map.

How Big Is The Difference? Our Speed Test

To see what O(log n) and O(1) mean in practice, we measured it. We inserted 1,000,000 random integer keys into each container and then looked up every one of them. The program was compiled with g++ 13 using the -O2 option, and we took the best time out of 3 runs.

ContainerInsert 1,000,000 KeysLook Up 1,000,000 Keys
map631 ms617 ms
unordered_map138 ms25 ms

These numbers are from one machine, and yours will be different. But the gap is clear. With a million keys, the unordered_map was several times faster in both tests. Keep in mind that integer keys are the best case for a hash table. With string keys, the gap is usually smaller.

Now, do not read too much into this. With 100 or even 10,000 keys, which is the size of a typical class assignment, both containers finish before you can notice. So, choose by the output you need. If the keys must come out sorted, use map. If the order does not matter and the data is large, use unordered_map.

Comparison Table Between C++ Dictionary And Python Dictionary:

Most of the time, we have seen that students get confused between the C++ Dictionary and the Python Dictionary. Instructors know this pattern and ask questions from this area of confusion.

So, to overcome such traps in your assignment, you have to know their differences. That is the reason we have brought a comparison table between the two C++ dictionaries and the Python dictionary.

FeatureC++ mapC++ unordered_mapPython dict
Header / Name<map><unordered_map>Built in, no import
OrderSorted by keyNo fixed orderInsertion order
ImplementationBalanced treeHash tableHash table
Search, Insert, DeleteO(log n)O(1) on averageO(1) on average
TypingStatic. One type for all keys, one type for all valuesStatic. One type for all keys, one type for all valuesDynamic. Keys and values can be of mixed types
Reading A Missing Key[] creates it, at() throws[] creates it, at() throwsRaises KeyError
Assigning To Another VariableMakes a full copyMakes a full copyBoth names point to the same dict
Best Used WhenSorted output is neededFast lookup is needed and order does not matterGeneral use in Python

If someone asks which C++ container is closest to the Python dictionary, the answer is unordered_map, because both are hash tables. But remember that the Python dictionary keeps the insertion order (from Python 3.7), and the unordered_map does not.

Real Assignment Question: C++ Program To Remove An Element From A Dictionary For Assignments

I have seen many times that the question sometimes asks to remove an element from the dictionary instead of creating it. This is where most students get stuck and fail to submit the code.

To deal with such issues, we use the erase() function. Let us check its implementation process.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    // Declaring A Map As A Dictionary
    map<string, int> age;

    // Adding Elements To The Dictionary
    age["Tom"] = 20;     
    age["Jerry"] = 18;   

    // Removing An Element From The Dictionary
    age.erase("Tom");  

    // Printing The Values
    for (auto item : age) {
        cout << item.first << " : " << item.second << endl;
    }

    return 0;
}
  • A dictionary is created using a map<string, int> where names are keys and ages are values.
  • The erase("Tom") function removes the entry with the key "Tom".
  • After deletion, the loop prints the remaining elements in the dictionary.

Output:

Jerry : 18

What happens if we try to remove a key that is not present? Nothing breaks. The erase() function returns the number of elements it removed, so we get 0. The following program shows this, along with the size(), clear(), and empty() functions.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> age = {{"Tom", 20}, {"Jerry", 18}, {"Spike", 25}};

    // erase() Returns How Many Elements It Removed
    cout << "Removing Tom: " << age.erase("Tom") << endl;
    cout << "Removing Butch: " << age.erase("Butch") << endl; // Not Present, So 0

    cout << "Size Now: " << age.size() << endl;

    age.clear(); // Removing Everything
    cout << "Size After clear(): " << age.size() << endl;
    cout << "Is It Empty? " << (age.empty() ? "Yes" : "No") << endl;
    return 0;
}

Output:

Removing Tom: 1
Removing Butch: 0
Size Now: 2
Size After clear(): 0
Is It Empty? Yes

Real Assignment Question: Count The Frequency Of Each Word

This is one of the most common dictionary questions in C++ courses. A sentence is given, and we have to print how many times each word appears. With a Dictionary, the main logic is only one line.

#include <iostream>
#include <map>
#include <sstream>
#include <string>
using namespace std;

int main() {
    string text = "the cat and the dog and the bird";
    map<string, int> freq; // Word Is The Key, Number Of Times Is The Value

    stringstream ss(text);
    string word;
    while (ss >> word) {
        freq[word]++; // A New Word Starts At 0, Then Becomes 1
    }

    for (auto item : freq) {
        cout << item.first << " : " << item.second << endl;
    }
    return 0;
}

Output:

and : 2
bird : 1
cat : 1
dog : 1
the : 3

Steps Of The Program:

  • We put the sentence into a stringstream and take out one word at a time.
  • For each word, we write freq[word]++. Here, the behavior of the square brackets helps us. If the word is new, the map creates it with the value 0, and the ++ makes it 1. If the word is already present, its count goes up by 1.
  • In the end, we print all the pairs. As it is a map, the words come out in alphabetical order.

The same program counts characters if we change the key type to char and loop over the string. If the words in your input are separated by commas or other symbols, our guide on how to split a string in C++ shows how to break the text first.

How To Sort A C++ Dictionary By Value?

A map is always sorted by its keys, and it cannot be sorted by its values. But assignments often ask for the output by value, for example, students from the highest score to the lowest. For that purpose, there is a need to copy the pairs into a vector and sort the vector.

#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;

int main() {
    map<string, int> scores = {{"Newton", 85}, {"Tom", 90}, {"Spike", 78}, {"Jerry", 95}};

    // Step 1: Copy The Pairs Into A Vector
    vector<pair<string, int>> pairs(scores.begin(), scores.end());

    // Step 2: Sort The Vector By The Second Part Of Each Pair, Highest First
    sort(pairs.begin(), pairs.end(), [](const pair<string, int>& a, const pair<string, int>& b) {
        return a.second > b.second;
    });

    // Step 3: Print The Sorted Vector
    for (auto item : pairs) {
        cout << item.first << " : " << item.second << endl;
    }
    return 0;
}

Output:

Jerry : 95
Tom : 90
Newton : 85
Spike : 78

The Dictionary itself is not changed by this. Only the vector is sorted. If we want the lowest score first, we change the > sign inside the sort to a < sign.

Can A C++ Dictionary Hold A List As A Value Or My Own Type As A Key?

Yes, both are possible. The value can be any type, including a vector. This is how we store several values under one key.

#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;

int main() {
    // One Key Can Hold A Whole List Of Values
    map<string, vector<string>> courses;

    courses["Tom"].push_back("Math");
    courses["Tom"].push_back("Physics");
    courses["Jerry"].push_back("Biology");

    for (auto item : courses) {
        cout << item.first << " Takes: ";
        for (auto name : item.second)
            cout << name << " ";
        cout << endl;
    }
    return 0;
}

Output:

Jerry Takes: Biology
Tom Takes: Math Physics

The key can also be a struct that we have made ourselves. But here, there is a condition. A map keeps its keys sorted, so it must know how to compare two keys. If we use a plain struct as the key, the compiler stops with a long error, and this line is the important part of it:

/usr/include/c++/13/bits/stl_function.h:408:20: error: no match for 'operator<' (operand types are 'const Seat' and 'const Seat')

To fix it, we have to write the ‘<’ operator for our struct, as the following program does.

#include <iostream>
#include <map>
#include <string>
using namespace std;

struct Seat {
    int row;
    int number;

    // The Map Needs This To Decide Which Key Comes First
    bool operator<(const Seat& other) const {
        if (row != other.row)
            return row < other.row;
        return number < other.number;
    }
};

int main() {
    map<Seat, string> booking;

    booking[{2, 5}] = "Tom";
    booking[{1, 9}] = "Jerry";
    booking[{1, 3}] = "Spike";

    for (auto item : booking) {
        cout << "Row " << item.first.row << ", Seat " << item.first.number
             << " : " << item.second << endl;
    }
    return 0;
}

Output:

Row 1, Seat 3 : Spike
Row 1, Seat 9 : Jerry
Row 2, Seat 5 : Tom

For an unordered_map, the requirement is different. It needs a hash function and the ‘==’ operator for the key type. That takes more code, so for your own struct as a key, the map is the easier choice.

Common Mistakes Students Make With C++ Dictionary Assignment:

Since we have checked many assignments and homework on the C++ dictionary, we can confidently say that there are some common mistakes that most students make.

So, to warn you again, we have brought this section, which will help you to avoid making them.

  • Students often forget to include the correct header file, such as <map> or <unordered_map>, causing compilation errors.
  • Beginners assume that unordered_map maintains insertion order, which it does not.
  • Students confuse first and second while accessing key-value pairs inside loops. Remember, first is the key and second is the value.
  • Using the wrong data type for keys or values often leads to logical errors.
  • Some students modify a map while iterating over it, which can cause unexpected behavior.
  • Many students check a key with the square brackets, like if (age["Spike"] == 0). This adds "Spike" to the Dictionary, and an extra row shows up when the Dictionary is printed later.
  • Students expect the map to print in the order they inserted the data. A map prints in sorted key order, and neither map nor unordered_map remembers the insertion order.
  • Some students use insert() to update a value and wonder why nothing changed. As shown above, insert() does not overwrite.

These header-file and first/second slip-ups are exactly what cost points in C++ submissions. If your map code won't compile and you can't see why, our team can find the broken line and explain the fix.

Conclusion:

Understanding how C++ implements dictionary-like behavior helps students write efficient code and choose the right data structure in exams and real applications.

We need to remember those highlights related to the Dictionary in the C++ programming language. It will make it easier for us to memorize the process.

There is a need to clear the basics of the C++ programming language to get this topic more easily. There is a need to start this topic from scratch to better understand it. We need to remember that there is no concept of a Dictionary present in the C++ Programming Language. It is a concept that will be of use to us in the future.

So, hope you have liked this blog. Share your thoughts in the comments section and let us know if we can improve further.

This concept is widely used in data structures coursework, competitive programming, and real-world systems that require fast data lookup.

Key Takeaways:

  • C++ does not have a built-in dictionary, but map and unordered_map provide key-value storage.
  • Both map and unordered_map are part of the C++ Standard Template Library (STL).
  • Elements in a map are stored in sorted order, while unordered_map uses hashing and does not maintain order.
  • Key-value pairs are added using map[key] = value, and accessed with loops using .first for keys and .second for values.
  • Reading a missing key with the square brackets creates that key. Use at(), find(), or count() when you only want to read or check.
  • A new dictionary can be created from an existing one by copying the original map.
  • Common mistakes include forgetting header files, misusing .first and .second, using the wrong data types, etc.

Frequently Asked Questions

1) Can we use a Python dictionary directly in C++?

No, C++ does not support Python-style dictionaries directly. Instead, we use containers like map or unordered_map from the Standard Template Library (STL), which allow us to store and access data.

2) What is the difference between map and unordered_map in C++?

A map stores its elements in sorted order based on the keys, while an unordered_map stores elements using hashing, which does not maintain any order. Map is slower than unordered_map because it has to keep the keys sorted.

3) Can a C++ dictionary store duplicate keys?

No, in C++ dictionaries, each key must be unique. If you assign a value to an existing key with the square brackets, it will overwrite the previous value associated with that key. If you use insert() with an existing key, nothing changes. If you really need duplicate keys, use a multimap.

4) Is unordered_map better than map for assignments?

Unordered_map is not always better than map for assignments. It depends on what the question requires. If the assignment asks for faster searching or counting frequency on a large input, then unordered_map is a better choice. If it asks for sorted output, use map.

5) Is there a dictionary data type in C++?

No. There is no type named dictionary or dict in C++. The map and unordered_map containers do the same job. Both store key-value pairs and let us find a value by its key.

6) Why did my C++ dictionary get an extra key with the value 0?

Because the key was read with the square brackets before it existed. The [] operator creates a missing key with a default value, which is 0 for numbers and an empty string for strings. To check or read without creating, use count(), find(), or at().

7) Does a C++ map keep the order in which I inserted the elements?

No. A map keeps its keys in sorted order, and an unordered_map has no fixed order. If you need the insertion order, store the keys in a vector as you insert them, and use that vector to loop over the map.