← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 10 of 15

C++ unordered_map

What is unordered_map?

std::unordered_map is an associative container storing key-value pairs with no guaranteed order, implemented as a hash table. Average-case lookup, insertion, and deletion run in O(1) time, faster than map for most workloads that do not need sorted keys.

Example: What is unordered_map?

cpp
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
	std::unordered_map<std::string, int> ages;
	ages["Alex"] = 30;
	std::cout << ages["Alex"] << std::endl;
	return 0;
}

Accessing Elements

Like map, unordered_map supports operator[] and at() for access. Since there is no ordering, elements are retrieved purely by key, not by position.

Example: Accessing Elements

cpp
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
	std::unordered_map<std::string, int> ages = {{"Alex", 30}};
	std::cout << ages.at("Alex") << std::endl;
	return 0;
}

Hashing & Performance

unordered_map hashes each key to determine its bucket. This gives average O(1) operations but worst-case O(n) if many keys collide. bucket_count() and load_factor() expose the internal hash table state.

Example: Hashing & Performance

cpp
#include <iostream>
#include <unordered_map>

int main() {
	std::unordered_map<int, int> m;
	m[1] = 10;
	std::cout << "buckets=" << m.bucket_count() << " load_factor=" << m.load_factor() << std::endl;
	return 0;
}

Iterating (Unordered)

Iterating an unordered_map visits elements in an unspecified, implementation-defined order that can change between insertions. Never rely on iteration order for correctness.

Example: Iterating (Unordered)

cpp
#include <iostream>
#include <unordered_map>

int main() {
	std::unordered_map<int, int> m = {{1, 10}, {2, 20}};
	for (const auto &[key, value] : m) {
		std::cout << key << ":" << value << " ";
	}
	std::cout << std::endl;
	return 0;
}

Searching and Erasing

find(), count(), and erase() work the same way as std::map, but rely on hashing rather than tree traversal, making them faster on average for large unsorted datasets.

Example: Searching and Erasing

cpp
#include <iostream>
#include <unordered_map>

int main() {
	std::unordered_map<int, int> m = {{1, 10}};
	auto it = m.find(1);
	if (it != m.end()) std::cout << "Found: " << it->second << std::endl;
	m.erase(1);
	std::cout << m.size() << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.