Tutorial by Examples

An std::map takes (key, value) pairs as input. Consider the following example of std::map initialization: std::map < std::string, int > ranking { std::make_pair("stackoverflow", 2), std::make_pair("docs-beta", 1) }; In an std::...
std::map and std::multimap both can be initialized by providing key-value pairs separated by comma. Key-value pairs could be provided by either {key, value} or can be explicitly created by std::make_pair(key, value). As std::map does not allow duplicate keys and comma operator performs right to left...
Removing all elements: std::multimap< int , int > mmp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} }; mmp.clear(); //empty multimap Removing element from somewhere with the help of iterator: std::multimap< int , int > mmp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} }; ...
An element can be inserted into a std::map only if its key is not already present in the map. Given for example: std::map< std::string, size_t > fruits_count; A key-value pair is inserted into a std::map through the insert() member function. It requires a pair as an argument: fruits_c...
std::map or std::multimap could be traversed by the following ways: std::multimap< int , int > mmp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} }; //Range based loop - since C++11 for(const auto &x: mmp) std::cout<< x.first <<":...
There are several ways to search a key in std::map or in std::multimap. To get the iterator of the first occurrence of a key, the find() function can be used. It returns end() if the key does not exist. std::multimap< int , int > mmp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} }; ...
The container std::map has a member function empty(), which returns true or false, depending on whether the map is empty or not. The member function size() returns the number of element stored in a std::map container: std::map<std::string , int> rank {{"facebook.com", 1} ,{"goo...
Regular Map A map is an associative container, containing key-value pairs. #include <string> #include <map> std::map<std::string, size_t> fruits_count; In the above example, std::string is the key type, and size_t is a value. The key acts as an index in the map. Each key mu...
In order to be able to use a class as the key in a map, all that is required of the key is that it be copiable and assignable. The ordering within the map is defined by the third argument to the template (and the argument to the constructor, if used). This defaults to std::less<KeyType>, w...

Page 1 of 1