4 ms·
operator[] is indeed not great, the semantics are too surprising for such a short-hand notation. auto [it, newly_created] = m.try_emplace(key); Does the sam
by planede 4y ago
operator[] is indeed not great, the semantics are too surprising for such a short-hand notation.
auto [it, newly_created] = m.try_emplace(key);
Does the same, and gives back more information. For something like `m[key] = value`, you can do `m.insert_or_assign(key, value)`, and save the default construction + assignment when the key was not there.
For ordinary lookup you don't want to randomly mutate the map anyway. If your reference to the map is const, you can't use operator[] anyway, fortunately. However `m.at(key)` is not great either when the key not being present is really not exceptional, and the dance with `m.find(key)` is often not too ergonomic. I still suggest to just use `find` here.