The map associative container (from header <map>
) performs fast storage and retrieval of unique keys and associated values. Duplicate keys are not allowed—a single value can be associated with each key. This is called a one-to-one mapping. For example, a company that uses unique employee numbers, such as 100, 200 and 300, might have a map
that associates employee numbers with their telephone extensions—4321, 4115 and 5217, respectively. With a map
you specify the key and get back the associated data quickly. Providing the key in a map
’s subscript operator []
locates the value associated with that key in the map
. Insertions and deletions can be made anywhere in a map
. If the order of the keys is not important, you can use unordered_map
(header <unordered_map>
) instead.
Figure 15.18 demonstrates a map
and uses the same features as Fig. 15.17 to demonstrate the subscript operator. Lines 27–28 use the subscript operator of class map
. When the subscript is a key that’s already in the map
(line 27), the operator returns a reference to the associated value. When the subscript is a key that’s not in the map
(line 18), the operator inserts the key in the map
and returns a reference that can be used to associate a value with that key. Line 27 replaces the value for the key 25
(previously 33.333
as specified in line 16) with a new value, 9999.99
. Line 28 inserts a new key–value pair
in the map
(called creating an association).
1 // Fig. 15.18: fig15_18.cpp
2 // Standard Library class map class template.
3 #include <iostream>
4 #include <map> // map class-template definition
5 using namespace std;
6
7 int main()
8 {
9 map< int, double, less< int > > pairs;
10
11 // insert eight value_type objects in pairs
12 pairs.insert( make_pair( 15, 2.7 ) );
13 pairs.insert( make_pair( 30, 111.11 ) );
14 pairs.insert( make_pair( 5, 1010.1 ) );
15 pairs.insert( make_pair( 10, 22.22 ) );
16 pairs.insert( make_pair( 25, 33.333 ) );
17 pairs.insert( make_pair( 5, 77.54 ) ); // dup ignored
18 pairs.insert( make_pair( 20, 9.345 ) );
19 pairs.insert( make_pair( 15, 99.3 ) ); // dup ignored
20
21 cout << "pairs contains:
Key Value
";
22
23 // walk through elements of pairs
24 for ( auto mapItem : pairs )
25 cout << mapItem.first << ' ' << mapItem.second << '
';
26
27 pairs[ 25 ] = 9999.99; // use subscripting to change value for key 25
28 pairs[ 40 ] = 8765.43; // use subscripting to insert value for key 40
29
30 cout << "
After subscript operations, pairs contains:
Key Value
";
31
32 // use const_iterator to walk through elements of pairs
33 for ( auto mapItem : pairs )
34 cout << mapItem.first << ' ' << mapItem.second << '
';
35
36 cout << endl;
37 } // end main