c++标准容器基础《set》

c++标准容器基础之set

set由一群key组合而成,如果我们想知道某值是否在于某个集合内,就可以使用set,在
图的遍历中,可以将已访问过的节点放入set,再向后遍历时可向集合中查询是否已遍历该
节点,本程序可统计侮辱性词汇之外的词汇及次数

使用set

//本程序可统计侮辱性词汇之外的词汇及次数
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;
int main()
{
	string tword;
	map<string, int>words;
	set<string>words_exclusion = {"gdx","fuck","shit","damn","motherfucker","five","laji"};//建立一个set并赋初值
	while (cin >> tword && tword!="#")
	{
		if (words_exclusion.count(tword))
			continue;
		words[tword]++;
	}
	map<string, int>::iterator it = words.begin(); //begin()指向第一个元素
	for (; it != words.end(); it++)  //begin()指向最后一个元素的下一个位置
		cout << "key:" << it->first << "   Times:" << it->second << endl;
	return 0;
}

set 常用函数

#include <iostream>
#include <set>
using namespace std;

void set_lianxi()
{
	set<int> num;
	for (int i = 9; i > 0; i--)
		num.insert(i);   //insert()表示向set中插入元素,且去除重复元素,按从小到大排列
	
	set<int>::iterator it = num.begin();
	for (; it != num.end(); it++)
		cout << *it << " ";   //访问set元素只能通过枚举,且用*it形式输出元素,与map不同
	cout << endl;

	it = num.find(3);
	cout << *it << endl;    //find(value)返回值为value的迭代器

	num.erase(num.find(4));   //erase(it)擦除it指向的元素
	for (it = num.begin(); it != num.end(); it++)
		cout << *it << " ";
	cout << endl;

	num.erase(5);   //erase(value)擦除元素value
	for (it = num.begin(); it != num.end(); it++)
		cout << *it << " ";
	cout << endl;

	it = num.find(6);
	num.erase(it, num.find(9));   //erase(first,last)表示删除泛型指针区间为[first,last)的元素
	for (it = num.begin(); it != num.end(); it++)
		cout << *it << " ";
	cout << endl;

	num.clear();
	cout << num.size() << endl;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值