Maps
A map holds a key-value pair, with the requirement that the key is unique.
Tip
A C++ map is functionally the same as a dictionary in python.
Here’s an example:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> a;
a["one"] = 1;
a["two"] = 2;
for (const auto& [key, value] : a) {
std::cout << "[" << key << "] = " << value << std::endl;
}
}
We use a structured binding to unpack the key and value into separate variables.
Tip
If we instead loop over our map, a, as:
for (auto e : a) {
...
}
Then e will be a std::pair object inside the loop. We would then
use e.first and e.second to access the key and value.
Notice that we can freely add to the map simply by using a new key.
In C++20, the contains() member function was added to maps to test
if a key is part of a map:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> a;
a["A"] = 1;
a["B"] = 2;
a["C"] = 3;
if (a.contains("D")) {
std::cout << "element D is a member of the map" << std::endl;
} else {
std::cout << "element D is not defined" << std::endl;
}
}
Tip
To compile this, you likely need to add -std=c++20 to the compilation
line.
For older versions of g++, you may instead need -std=c++2a.