ISO/IEC 14882 §23.4.4.3
T& operator[](const key_type& x);
- Effects: If there is no key equivalent to
x
in the map, insertsvalue_type(x, T())
into the map.- Requires:
key_type
shall beCopyConstructible
andmapped_type
shall beDefaultConstructible
.- Returns: A reference to the
mapped_type
corresponding tox
in*this
.- Complexity: logarithmic.
So, not only is it guaranteed, but evaluating myMap["Hey"]
also causes the value 0 to be inserted into the map, if there was no entry for it before.
所以,对于std::map可以直接进行加减,不需要初始化:
int main()
{
std::map<std::string, int> wordCount;
ifstream input;
input.imbue(std::locale(std::locale(), new letter_only())); //enable reading only letters!
input.open("filename.txt");
std::string word;
while(input >> word)
{
++wordCount[word];
}
for (std::map<std::string, int>::iterator it = wordCount.begin(); it != wordCount.end(); ++it)
{
cout << it->first <<" : "<< it->second << endl;
}
}