CSE 202: Computer Science II, Winter 2018
std::map

std::map is another standard C++ container like std::vector is. Unlike std::vector, std::map is not a sequence container; it is an associative container.

A map is instantiated with a key type and a mapped type. The element type of a map is a pair containing a key type value and a mapped type value. For example, the element type of std::map<std::string, double> is std::map<std::string, double>::value_type which is an alias for std::pair<const std::string, double>.

No two elements can contain the same key value in a map.

A map element can be accessed by specifying the key of that element. Map elements can be created or accessed with the subscript operator:

#include <map> #include <iostream> int main() { std::map<std::string, double> coins; // Creating map elements coins["penny"] = 1.0; coins["nickel"] = 5.0; coins["dime"] = 10.0; coins["quarter"] = 25.0; //Iterating through map elements for (std::map<std::string, double>::iterator it = coins.begin(); it != coins.end(); ++it) { std::cout << it->first << " -> " it->second << std::endl; } return 0; }

For each pair stored in a map, the data member first refers to the key value and the data member second refers to the mapped value. Once an element is created, it's key value cannot be changed.

Map operations

Suppose there is a std::map<std::string, std::string> m, then the following operations are supported:

Expression Meaning
m["foo"] Accesses the element containing the key value "foo", creating the element if it doesn't exist.
m.begin() Returns an iterator to the first element
m.end() Returns an iterator that follows the last element
m.empty() Returns true if m contains zero elements
m.size() Returns the number of elements in m
m.clear() Erases all elements from m
m.insert(x) Inserts the value x into m. Equivalent to m[x.first] = x.second
m.insert(first, last) Inserts the values within the range [first, last) into m. Equivalent to while (first != last) m.insert(*first++);
m.erase("foo") Erases the element containing the key value "foo"
m.erase(it) Erases the element specified by the iterator it.
m.erase(first, last) Erases the elements within the range [first, last) from m.
m.swap(n) Swaps the contents of maps m and n
m.find("foo") Returns an iterator to the element containing the key value "foo". Returns m.end() if the element was not found.