Why is there no [] operator for std::multimap?
In errors with multimap (key type is std::string), people say "it makes no sense to extract elements out of it -- there are multiple values per each index". To me, it makes perfect sense and this is why there is equal_range.
So, why did they decided not to add a [] operator for multimap then?
I feel it is because things like myMultiMap[key] = value
would be complex to handle but I am really not sure about that.
Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function Compare , applied to the keys. Search, insertion, and removal operations have logarithmic complexity.
Multimaps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order, and where multiple elements can have equivalent keys.
Multimaps are part of the C++ STL (Standard Template Library). Multimaps are the associative containers like map that stores sorted key-value pair, but unlike maps which store only unique keys, multimap can have duplicate keys. By default it uses < operator to compare the keys.
1) A std::multimap is only ordered by its keys and you can't reorder it after it's built. 2) You couldn't use std::sort for this anyway because it requires random access iterators and std::multimap only provides bidirectional iterators.
This might be because of ambiguity as multiMap[key] can represent many elements depending upon the number of insertion with same key.
The operator[] always returns an lvalue reference to the element present at provided index of any randomly accessible container(s), so in case of multimap(s) there will be more than one element for the same key.
Note this is not same as the collision in a HashTable based container (std::unordered_map, std::unordered_set) where different keys can have same hash value computed from a hash function causing elements to land in same bucket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With