#include<iostream>
#include<map>
#include<string>
#include<cstddef>
#include<set>
using namespace std;
//void main()
//{
// map<string, string> phonebook;
// phonebook.insert(pair<string,string>("songji", "123456879"));
// //phonebook.insert(make_pair<string,string>("sj", "159467893"));
// phonebook.insert(make_pair("sj", "159467893")); //不需要传入参数类型
// phonebook.insert(map<string, string>::value_type("songji", "123456879"));
// for (auto out : phonebook)
// cout << out.first << " " << out.second << endl;
//}
//int main()
//{
// string word;
// map<string,int> word_count;
//
// while(cin >> word)
// {
// pair<map<string,int>::iterator,bool> p = word_count.insert(make_pair(word,1));
//insert(或者emplace)返回的值依赖于容器类型和参数。对于不包含重复关键字的容器,添加单一元素的insert和emplace版本返回一个pair。
//pair的first成员是一个迭代器,指向具有给定关键字的元素;
//pair的second成员是一个bool值,指出元素是插入成功还是已经在容器中。
//如果关键字已经在容器中,则insert什么事情也不做,且返回值中的bool部分为false。
//如果关键字不在容器中,元素被插入到容器中,且bool值为true。
// if(p.second == false)
// {
// ++p.first->second; //++(*(p.first).second);
// }
// }
//
// for(map<string,int>::iterator flag=word_count.begin();flag!=word_count.end();flag++)
// cout << flag->first << " " << flag->second << endl;
//}
void main()
{
/*map<int, int> num;
int xuehao;*/
map<string, size_t> word_count;
string word;
set<string> exclude = { "the", "a", "an", "The", "A", "An" }; //排除指定的要统计的单词的集合
while (cin >> word)
{
if (exclude.find(word)==exclude.end()) //当在exclude的set中找不到“word”,find才会返回end,下面语句才会执行
++word_count[word]; //在set找见,则不会执行,也就实现了设定的忽略统计单词的集合
//提取word的计数器,并对其加1;
//当对word_count进行下标操作时,我们使用一个string作为下标,获得与此string相关联的size_t类型的计数器
}
for (const auto &w : word_count) //当对map中提取一个元素时,会得到一个pair类型的对象(first成员保存关键字,second成员保存对应的值)
cout << w.first << "\t" << w.second << ((w.second) > 1 ? "times" : "time") << endl;
}
map、set例子
最新推荐文章于 2022-12-01 00:25:51 发布