std::map and std::unordered_map: dictionaries
A vector is useful when you access data by position, but often you want to search by a key: the price of a product by its name, the age of a person by an identifier, how many times each word appears in a text. For that the STL offers associative containers, which store key-value pairs. Today we study the two most used: std::map, which keeps keys sorted, and std::unordered_map, which uses a hash table and is usually faster for lookups. Both live in their own headers, <map> and <unordered_map>.
Creating and traversing a map
It is declared with the key type and the value type: std::map<std::string, int> stock;. You can initialize it with braces, each pair in its own braces: {{"apple", 10}, {"pear", 4}}. The [] operator looks up the key and, if it does not exist, creates it with a default value (0 for numbers), and returns a reference to the value; that is why stock["kiwi"] = 7; inserts or updates. When traversing with a range-based for, each element is a std::pair with members first (the key) and second (the value). Since C++17 you can use structured bindings: for (const auto& [name, qty] : stock), much more readable. In std::map the traversal always comes out sorted by key.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> stock{{"apple", 10}, {"pear", 4}};
stock["kiwi"] = 7; // inserts a new key
stock["pear"] += 6; // updates an existing value: 4 -> 10
for (const auto& [name, qty] : stock) {
std::cout << name << " -> " << qty << '\n';
}
// apple -> 10
// kiwi -> 7
// pear -> 10
std::cout << "size = " << stock.size() << '\n'; // size = 3
return 0;
}Looking up without creating: find, count and at
The [] operator has a dangerous side effect: if you query a key that does not exist, it creates it. If you only want to check, use count(key), which returns 0 or 1, or find(key), which returns an iterator to the element or end() if it is missing. To read a value that must exist, at(key) throws std::out_of_range when missing, which is better than an invented value. To insert without overwriting use insert or try_emplace (C++17); to delete, erase(key). A very typical mistake: writing if (stock["mango"] > 0) to check inventory, which besides checking adds "mango" to the map with value 0. The fix is to use find or count.
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
int main() {
std::map<std::string, int> stock{{"apple", 10}, {"pear", 4}};
auto it = stock.find("apple");
if (it != stock.end()) {
std::cout << "apple: " << it->second << '\n'; // apple: 10
}
if (stock.count("mango") == 0) {
std::cout << "no mango\n"; // no mango
}
stock.try_emplace("pear", 99); // pear already exists: nothing changes
stock.erase("apple");
try {
std::cout << stock.at("apple") << '\n';
} catch (const std::out_of_range&) {
std::cout << "apple was removed\n"; // apple was removed
}
std::cout << "pear = " << stock["pear"] << '\n'; // pear = 4
return 0;
}unordered_map and when to choose each one
std::unordered_map offers almost the same interface, but organizes data with a hash function: lookup, insertion and deletion cost constant time on average, while in std::map (a balanced tree) they cost logarithmic time. In exchange, the traversal order of unordered_map is unspecified and you must not depend on it. Practical rule: use unordered_map by default when you only search by key; use map when you need sorted traversal, range searches or the smallest key. The keys of a map must be comparable with <, and those of an unordered_map need a hash function, which the library already provides for integers and strings.
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
int main() {
std::string text{"the cat and the dog and the bird"};
std::istringstream words{text};
std::unordered_map<std::string, int> counts;
std::string word;
while (words >> word) {
++counts[word]; // creates with 0 the first time, then increments
}
// copy into a map to print in alphabetical order
std::map<std::string, int> sorted(counts.begin(), counts.end());
for (const auto& [w, n] : sorted) {
std::cout << w << ": " << n << '\n';
}
// and: 2
// bird: 1
// cat: 1
// dog: 1
// the: 3
return 0;
}✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères