Initializing a multimap or multiset
The keys in a map or a set must be unique; there can be only one element with a given key. The multimap and multiset containers have no such restriction; there can be several elements with the same key.
For the ordered containers―map, multimap, set, and multiset―the key type must define a way to compare the elements. By default, the library uses the
we can also supply our own operation to use in place of the
// bookstore can have several transactions with the same ISBN
// elements in bookstore will be in ISBN order
multiset
we use decltype to specify the type of our operation, remembering that when we use decltype to form a function pointer, we must add a * to indicate that we’re using a pointer to the given function type.
Pair is a template from which we generate specific types.
pair
pair
The library defines only a limited number of operations on pairs, which are listed in Table 11.2
Under the new standard we can list initialize the return value:
pair
{
// process v
if (!v.empty())
return {v.back(), v.back().size()}; // list initialize
else
return pair
}
In addition to the types listed in Table 9.2(p. 330), the associative containers define the types listed in Table 11.3.
set
set
map
map
map
When we dereference an iterator, we get a reference to a value of the container’s value_type. In the case of map, the value_type is a pair in which first holds the const key and second holds the value:
// get an iterator to an element in word_count
auto map_it = word_count.begin();
// *map_it is a reference to a pair
cout << map_it->first; // prints the key for this element
cout << " " << map_it->second; // prints the value of the element
map_it->first = "new key"; // error: key is const
++map_it->second; // ok: we can change the value through an iterator
It is essential to remember that the value_type of a map is a pair and that we can change the value but not the key member of that pair.
Although the set types define both the iterator and const_iterator types, both types of iterators give us read-only access to the elements in the set. Just as we cannot change the key part of a map element, the keys in a set are also const.
// get an iterator positioned on the first element
auto map_it = word_count.cbegin();
// compare the current iterator to the off-the-end iterator
while (map_it != word_count.cend()) {
// dereference the iterator to print the element key--value pairs
cout << map_it->first << " occurs "<< map_it->second << " times" << endl;
++map_it; // increment the iterator to denote the next element
}
When we use an iterator to traverse a map, multimap, set, or multiset, the iterators yield elements in ascending key order.
Associative Containers and Algorithms
In general, we do not use the generic algorithms (Chapter 10) with the associative containers. The fact that the keys are c