码迷,mamicode.com
首页 > 其他好文 > 详细

使用关联容器

时间:2020-03-15 13:15:43      阅读:42      评论:0      收藏:0      [点我收藏+]

标签:and   mes   out   word   ==   set   关联   time   clu   

使用 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;

使用关联容器

标签:and   mes   out   word   ==   set   关联   time   clu   

原文地址:https://www.cnblogs.com/xiaojianliu/p/12496898.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!