EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.
What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)
#include <map>
#include <string>
#include <iostream>
int
main(int argc, char** argv)
{
std::multimap<std::string, std::string> m;
m.insert(std::make_pair("A", "B"));
m.insert(std::make_pair("A", "B"));
m.insert(std::make_pair("A", "C"));
std::cout << m.size() << std::endl;
return 0;
}
This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.
Intuitively, it's not consistent with C++ std::map
behaviour, where insert
does not always change the map (as opposed to operator[]
).
Is there a rationale behind it, or it's just arbitrary?
Multimap only has a predicate ordering the keys. It has no method to determine whether the values are equal. Is value "A" a duplicate of value "a"? Without a second predicate for the values, there's no telling. Therefore, it doesn't even make sense to talk about duplicate values in a multimap.
If you would like a container that stores pairs, and enforces the unique-ness of both parts of the pair, look at boost::multi_index_container
. It's very flexible, but takes a load of arguments as a result.