C++ standard for "26.4.5.1 Class template multimap overview" p1 says:
A multimap is an associative container that supports equivalent keys (possibly containing multiple copies of the same key value) and provides for fast retrieval of values of another type T based on the keys.
emphasis is mine. So does it mean that std::multimap
may not keep a copy of original key object when inserted into equal range and replace it with equal one?
PS To make clear this question is inspired by this Does Each Element of a multimap Contain Both the Key and Value? and I want to know if multimap allowed to do that ie can I rely on its ability to maintain my key (which could be equal but not the same).
No. The standard describes how an element is inserted in this table. For example, the effect of a_eq.emplace(args)
is described as follows (emphasis mine).
Effects: Inserts a
value_type
objectt
constructed withstd::forward<Args>(args)...
and returns the iterator pointing to the newly inserted element. If a range containing elements equivalent tot
exists ina_eq
,t
is inserted at the end of that range.
Note the value_type
of std::multimap<Key, T>
is std::pair<const Key, T>
, so a same (not only equivalent) key must be constructed.
No, it doesn't mean that. multimap
has to have a key associated with the object for every element. Here is normative wording:
26.4.5.1: A multimap is an associative container that supports equivalent keys (possibly containing multiple copies of the same key value)...
26.2.6: The phrase “equivalence of keys” means the equivalence relation imposed by the comparison object. That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false. [ Note: This is not necessarily the same as the result of k1 == k2. — end note ] For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.
Since find
and friends are required to return elements with their respective keys (also preserving relative ordering of equivalent elements!), there is no way conformant multimap can store a single key.
来源:https://stackoverflow.com/questions/49696603/does-stdmultimap-guarantee-actual-value-of-each-key-in-equal-range