std::map

std::map is an associative container which is split into key / value pairs with unique keys.

std::map stores keys sorted ascending by default. It is very fast to search for elements as the key set is ordered and it can store duplicate values. Keys can be any type.

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> data {{1, "Hello"}, {2, "World"}};

    data[3] = "And";
    data[4] = "Goodbye";

    for (auto [key, value]: data) {
        std::cout << key << " : " << value << std::endl;
    }
    
    return 0;
}

Some common methods of the std::map type are insert, which inserts one or more key / value pairs into the map. Insert returns a pair which holds the state of the insert. In the first position, and the data inserted in the second position, a boolean indicating success., Emplace, which does the same as insert but builds the object in place, size, which returns how many items are in the map. We can use the [] operator or at() to add, amend, and access elements. We can loop a set using both a standard and enhanced for loop. Set supports both forward and reverse iterators.

There is also a multimap that allows duplicate keys but doesn’t have the [] operator or at() method.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.