That would render operator[] completely pointless. If you had to insert() an element before accessing it with operator[], then the only possible use of operator[] would be for lookup. I hardly see the point of even having an operator[] unless I can do this:
You certainly would be able to do that, just that there has to be a valid key with b's value already in the map. It would just make it inconvenient for insertion, so my example would become the rather horrible:
Code:
for (std::vector<std::string>::const_iterator i = words.begin(),
end = words.end(); i != end; ++i)
{
try
{
++word_count[*i];
}
catch (const std::out_of_range& e)
{
word_count.insert(std::make_pair(*i, 1));
}
}
... which would be about the same as just writing:
Code:
for (std::vector<std::string>::const_iterator i = words.begin(),
end = words.end(); i != end; ++i)
{
std::map<std::string, std::size_t>::iterator iter = word_count.find(*i);
if (iter != word_count.end())
{
++iter->second;
}
else
{
word_count.insert(std::make_pair(*i, 1));
}
}