Unlocking the Power of C++: A Deep Dive into Unordered Maps

What is an Unordered Map?

In C++, an unordered map is a type of associative container that stores elements in key-value pairs. Unlike a regular map, the order of keys in an unordered map is undefined, making it an efficient data structure for storing and retrieving data.

Creating an Unordered Map

To create an unordered map, you need to include the <unordered_map> header file and use the following syntax: unordered_map<key_type, value_type>. For example, unordered_map<string, int> would create an unordered map with string keys and integer values.

Initializing an Unordered Map

There are several ways to initialize an unordered map. You can provide values directly to the map, copy one map to another, or use structure bindings (available from C++17). Here’s an example of initializing an unordered map using uniform initialization:

unordered_map<string, int> unordered_map1 = {{"One", 1}, {"Two", 2}, {"Three", 3}};

Unordered Map Methods

The unordered_map class provides various methods to perform different operations on an unordered map. These include:

Inserting Key-Value Pairs

You can insert key-value pairs using the insert() method or the [] operator. For example:

unordered_map<string, int> unordered_map1;
unordered_map1["One"] = 1;
unordered_map1.insert({"Two", 2});

Accessing Values

You can access the values of an unordered map using the at() method or the [] operator. For example:

unordered_map<string, string> capital_city = {{"Nepal", "Kathmandu"}, {"Australia", "Canberra"}};
string city = capital_city.at("Nepal"); // returns "Kathmandu"
city = capital_city["Australia"]; // returns "Canberra"

Changing Values

You can change the values of an unordered map using the at() method or the [] operator. For example:

unordered_map<string, string> capital_city = {{"India", "Calcutta"}, {"Pakistan", "Karachi"}};
capital_city["India"] = "New Delhi";
capital_city.at("Pakistan") = "Lahore";

Removing Elements

You can remove elements from an unordered map using the erase() method. For example:

unordered_map<string, string> student = {{"143", "Chris"}, {"132", "Mark"}, {"111", "John"}};
student.erase("143"); // removes the element with key "143"

Checking if a Key Exists

You can check if a key exists in an unordered map using the find() method or the count() method. For example:

unordered_map<string, string> student = {{"143", "Chris"}, {"132", "Mark"}, {"111", "John"}};
auto it = student.find("143"); // returns an iterator pointing to the element if it exists
int count = student.count("1433"); // returns 0 if the key doesn't exist

Leave a Reply

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