Maps in C++

Based on the given input, the target language specified is cpp. Below is the translated Go code example to C++ along with the explanation in Markdown format suitable for Hugo.


Maps are C++’s built-in associative data type (sometimes called hashes or dicts in other languages).

To create an empty map, use the std::map:

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> m;

    // Set key/value pairs using typical name[key] = val syntax.
    m["k1"] = 7;
    m["k2"] = 13;

    // Printing a map with e.g. std::cout will show all of its key/value pairs.
    for (const auto &pair : m) {
        std::cout << "map: " << pair.first << " " << pair.second << std::endl;
    }

    // Get a value for a key with name[key].
    int v1 = m["k1"];
    std::cout << "v1: " << v1 << std::endl;

    // If the key doesn’t exist, the zero value of the value type is returned.
    int v3 = m["k3"];
    std::cout << "v3: " << v3 << std::endl;

    // The builtin size() returns the number of key/value pairs when called on a map.
    std::cout << "len: " << m.size() << std::endl;

    // The map's erase() function removes key/value pairs from a map.
    m.erase("k2");
    for (const auto &pair : m) {
        std::cout << "map: " << pair.first << " " << pair.second << std::endl;
    }

    // To remove all key/value pairs from a map, use the clear() function.
    m.clear();
    std::cout << "map size after clear: " << m.size() << std::endl;

    // The count() function indicates if the key was present in the map.
    bool prs = m.count("k2");
    std::cout << "prs: " << prs << std::endl;

    // You can also declare and initialize a new map in the same line with this syntax.
    std::map<std::string, int> n = { {"foo", 1}, {"bar", 2} };
    for (const auto &pair : n) {
        std::cout << "map: " << pair.first << " " << pair.second << std::endl;
    }

    // To compare maps, you need to iterate through and compare manually.
    std::map<std::string, int> n2 = { {"foo", 1}, {"bar", 2} };
    if (n == n2) {
        std::cout << "n == n2" << std::endl;
    }

    return 0;
}

To compile and run the C++ program, use the commands below:

$ g++ -o maps maps.cpp
$ ./maps

Running the program will produce the following output:

map: k1 7
map: k2 13
v1: 7
v3: 0
len: 2
map: k1 7
map: k2 not found 
map size after clear: 0
prs: 0
map: bar 2
map: foo 1
n == n2

Now that we can run and build basic C++ programs with maps, let’s learn more about the language.