is insert() necessary in a map or unordered_map?
c++
Solution
They are not.
`operator[]` will overwrite the value for this key, if it exists, while `insert` will not.
In case `operator[]` is used for inserting element, it is expected to be a little slower (see @MatthieuM's comment below for details), but this is not that significant here.
While `std::map::insert` returns `std::pair< iterator, bool >`, where the `.second` will tell you if the value is inserted or it already exists.
Regarding your comment: you cannot have 2 elements with the same key and different value. This is not a `multimap`.
If there's an element in the map, with the same key you're trying to insert, then:
- `operator[]` will overwrite the existing value
- `std::map::insert` will not do anything.* return a `std::pair< iterator, bool >`, where the `.second` will be `false` (saying "the new element is not inserted, as such key already exists") and the `.first` will point to the found element.
* I changed this thanks to the note/remark, given from @luk32; but by writing "will not do anything", I didn't mean it literally, I meant that it will not change the value of the existing element
Problem
I see a lot of examples that add items to a `map` or `unordered_map` via `operator[]`, like so: ``` int main() { unordered_map <string, int> m; m["foo"] = 42; cout << m["foo"] << endl; } ``` Is there any reason to use the `insert` member function instead? It would appear they both do the same thing.