练习 11.20:重写11.1节练习(第376)的单词计数程序,使用insert代替下标操作。你认为哪个程序更容易编写和阅读?解释原因。
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, size_t> word_count;
string word;
while (cin >> word)
{
auto index = word_count.insert({word, 1});
if(!index.second)
++index.first->second;
}
for (const auto &w : word_count)
{
cout << "\"" << w.first << "\" occurs: " << w.second
<< ((w.second > 1) ? " times" : " time") << endl;
}
return 0;
}