C++ unordered_map (C++11) šŸŽÆ

beginner
6 min

C++ unordered_map (C++11) šŸŽÆ

Welcome to our deep dive into the unordered_map data structure in C++! In this tutorial, we'll explore how to use this powerful tool, its benefits, and practical examples to help you master it.

What is an unordered_map? šŸ“

An unordered_map is a type of associative container in C++ that stores key-value pairs. Unlike a standard map, an unordered_map uses a hash function to organize its elements, providing faster search and insert operations.

Why Use unordered_map? šŸ’”

The main advantage of unordered_map is its speed. Since it uses a hash function for organization, it can perform searches and insertions in O(1) average time. This is a significant improvement over the O(log n) time of a standard map.

Creating an unordered_map šŸ“

To create an unordered_map, you first need to include the <unordered_map> header. Then, you can declare an unordered_map and initialize it with the desired key and value types.

cpp
#include <unordered_map> std::unordered_map<std::string, int> myMap;

In this example, we've created an unordered_map that stores strings as keys and integers as values.

Adding and Accessing Elements šŸ“

To add an element to an unordered_map, use the [] operator. This operator also checks if the key already exists and allows you to update its value.

cpp
myMap["apple"] = 10;

To access an element, use the [] operator again. If the key does not exist, the unordered_map will create a default-initialized value.

cpp
std::cout << myMap["orange"]; // Output: 0 (since no value was set for "orange")

Iterating Through an unordered_map šŸ“

You can iterate through an unordered_map using the begin() and end() functions, just like a standard map.

cpp
for (auto const& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; }

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What does an `unordered_map` provide over a standard `map` in terms of time complexity for search and insert operations?

Advanced Example šŸŽÆ

In this example, we'll create an unordered_map to store a frequency distribution of words in a text file.

cpp
#include <fstream> #include <unordered_map> #include <string> std::unordered_map<std::string, int> wordCount; void countWords(std::ifstream& file) { std::string word; while (file >> word) { ++wordCount[word]; } } int main() { std::ifstream inputFile("text.txt"); countWords(inputFile); for (auto const& pair : wordCount) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

In this example, we read a text file named text.txt and count the frequency of each word. The unordered_map is an excellent choice for this task due to its fast search and insert operations.

That's it for our C++ unordered_map tutorial! With this knowledge, you're well on your way to mastering this powerful data structure. Happy coding! šŸ’”šŸŽÆ