find(k) returns an iterator to the first pair that matches the key k. This means it's mostly useful when you want to check whether there is at least one value associated with the key or when you need only the first match. For example:
Handling Multiple Associated Values
The count(k) member function returns the number of values associated with a given key. The following example reports how many values are associated with the key 213.108.96.7:
cout<<dns.count("213.108.96.7") //output: 2
<<" elements associated"<<endl;
To access multiple values in a multimap, use the equal_range(), lower_bound() and upper_bound() member functions:
equal_range(k): This function finds all of the values associated with the key k. This function returns a pair of iterators that mark the beginning and the end of the range. The following example displays all the values associated with the key 213.108.96.7:
lower_bound() and upper_bound(): lower_bound(k) finds the first value associated with the key k, and upper_bound(k) finds the first element whose key is greater than k. The following example uses upper_bound() to locate the first element whose key is greater than 213.108.96.7. As usual, when the key is of type string a lexicographical comparison takes place:
If you wish to display all the subsequent values, use a loop like this:
//insert multiple values with the same key
dns.insert(make_pair("219.108.96.70",
"pythonzone.com"));
dns.insert(make_pair("219.108.96.70",
"python-zone.com"));
//get an iterator to the first value
CIT cit=dns.upper_bound("213.108.96.7");
//output: pythonzone.com python-zone.com
while(cit!=dns.end())
{
cout<<cit->second<<endl;
++cit;
}
Concept Mapping
Although map and multimap have similar interfaces, the crucial difference between the two, with respect to duplicate keys, entails different design and usage. In addition, you should be aware of the subtle differences between the insert() member function of each container.
Danny Kalev is a certified system analyst and software engineer specializing in C++ and theoretical aspects of formal languages. He was a member of the C++ standards committee between 1997 and 2000. He recently finished his MA in general linguistics summa cum laude. In his spare time he likes to listen to classical music, read Victorian literature and explore natural languages such as Hittite, Basque and Irish Gaelic. Additional interests include archeology and geology. Danny moderates several C++ forums and contributes regularly to various C++-related sites and magazines. He also gives lectures about programming languages and applied linguistics at academic institutes.