I have a map that I need to add and edit data. The problem is that I don't always know if I'm adding or editing.
As I understand, the .insert() function fails when the key already exists, and the [] operator will either insert or edit, depending whether or not it exists.
My question is twofold:
At the points where I know I'm inserting, is either method better?
At the pints where I don't know, is it better to use find and insert or use the [] operator, or is it just as well to just use the [] operator, and let the backend do the work?
Obviously, just using [] would be shorter, and logically (In my mind) faster, but my logic doesn't always match the STL, so I figured I should ask.
The only time (that I can think of) where operator[] can be useful is when you want to set the value of a key (overwrite it if it already has a value), and you know that it is safe to overwrite
That is my exact situation. The keys are user inserted, i.e they enter a key, and then the program asks for the value. So using the [] operator is a good, safe way for me to do it? I have no concerns for overwriting data.
So this problem was about recording the positions of words in a file. A map of vectors was used, the word is the key, and it's position the value pushed into the vector. The operator[] was convenient because if it was an existing word, then the position of it would be pushed into the vector for that key, otherwise the [] would return a new key and the word's position pushed into it's vector.
So it might depend on what the type of the map value is: POD; a class object; or a container; or combinations of these. And what the meaning (or consequences) of a duplicate map key is.
There is also std::multimap, std::unordered_map, and the idea that you can overload you own operator[] .
Any way I am sure you can figure all this out, it's just that there are different ways (of varying complexity) of thinking about it.
std::map<>::operator[]() requires that the mapped_type must be DefaultConstructible. If the key does not exist, it creates a key-data pair by default constructing the mapped_type, inserts the key-data pair into the map, and then returns a reference to the default constructed data.
std::map<>::emplace() allocates the requisite amount of memory and then constructs the key-data pair in-place.