Multimaps allow for multiple entries with the same key.
Here's a quick example to compare map and multimap funcitonality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <map>
int main()
{
std::map<std::string, int> m;
m.insert(std::pair<std::string, int>("a", 1)); //insert one item with key "a"
m.insert(std::pair<std::string, int>("a", 2)); //insert a second item with key "a"
for(auto &i: m)
cout << i.first << " " << i.second << endl;
return 0;
}
|
a 1 |
Regular maps will discard any any subsequent values inserted that have the same key. On the other hand, if you do the same thing with
std::multimap<std::string, int> m
instead, the output would be:
Multimaps allow any amount of values with the same key.
To get all values of key 'a', multimap provides the function
equal_range
(
http://www.cplusplus.com/reference/map/multimap/equal_range/)
that will give you a pair of iterators over the range of the specified key.
Consider the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <map>
int main()
{
//typedefs to reduce typing.
typedef std::multimap<std::string, int> mmap;
typedef std::pair<std::string, int> mmap_pair;
mmap m;
m.insert(mmap_pair("a", 1)); //insert a bunch of values
m.insert(mmap_pair("a", 2));
m.insert(mmap_pair("a", 3));
m.insert(mmap_pair("b", 4));
m.insert(mmap_pair("b", 5));
m.insert(mmap_pair("c", 6));
std::pair<mmap::iterator, mmap::iterator> range;
range = m.equal_range("a"); //equal_range returns pair of iterators
//loop through the iterator pair like regular iterators
for(mmap::iterator it = range.first; it != range.second; ++it)
std::cout << it->first << " " << it->second << endl;
return 0;
}
|
a 1
a 2
a 3 |
So you can do some cool things with multimaps.
That said, it's one of those containers you rarely need to use, but when you do need it, you
really need it.