> "preventing themselves from accidentally mutating a variable" (when has that ever happened?)
I can't count the number of times I've seen someone new to the language use map::operator[] without realizing that it's a mutating operation.
I can't count the number of times I've seen someone new to the language use map::operator[] without realizing that it's a mutating operation.
for (const auto &thing: collection) {
counts[thing]++;
}
Works nicely, you don't have to check if it's already there before ++ing it. As long as you know that's what operator[] does, it comes in handy more than I would've expected.Another popular use case is something along the lines of:
std::unique_ptr<T>& ptr = ptrs[key];
if (ptr != nullptr) {
ptr = std::make_unique<T>(...);
}
That said, I don't know what behavior I'd want if maps didn't automatically insert an element when the key was absent. UB (as with vector)? Throw an exception? Report the incident to Stroustrop? All these options feel differently bad.