使用关联容器

使用 map

使用 map 为单词计数:

map<string, size_t>  word_count;
string word;
while (cin >> word)
++word_count[word];

for (const auto & w : word_count)
    cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;

使用 set

接上面的例子,只统计不在 set 中的单词:

map<string, size_t>  word_count;
set<string> exclude{"the","a","an","or","and"};
string word;
while (cin >> word)
{
    if(exclude.find(word) == exclude.end())
    ++word_count[word];
}   

for (const auto & w : word_count)
    cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;

猜你喜欢

转载自www.cnblogs.com/xiaojianliu/p/12496898.html