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