Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no [] operator for std::multimap?

Tags:

c++

c++11

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.

like image 440
Korchkidu Avatar asked Jan 08 '15 09:01

Korchkidu


People also ask

Is multimap sorted C++?

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.

What is STD multimap?

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.

What is the use of multimap in C++?

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.

Is an STD multimap sorted?

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.


1 Answers

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.

like image 97
titus Avatar answered Nov 15 '22 00:11

titus