map、set例子

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值