您的位置:首页 > 编程语言 > C语言/C++

C++中的关联容器set用法

2014-11-11 11:54 274 查看
定义
//define a vector with 20 elements, holding two copies of each number from 0 to 9
vector<int> ivec;
for(vector<int>::size_type i=0; i!=10; ++i){
ivec.push_back(i);
ivec.push_back(i); //duplicate copies of each number
}
//iset hold unique elements from ivec
set<int> iset(ivec.begin(), ivec.end());
cout<<ivec.size()<<endl; //print 20
cout<<iset.size()<<endl; //print 10

添加元素
set<string> set1; //empty set
set1.insert("the"); //set1 now has one element
set1.insert("and"); //set1 now has two elements

set<int> set2; //empty set
set2.insert(iset.begin(), iset.end()); //set2 now has 10 elements

获取元素
iset.find(1); //returns iterator that refers to the element with key==1
iset.find(11); //returns iterator == iset.end()
iset.count(1); //returns 1;
iset.count(11); //returns 0;

//set_it refers to the element with key==1
set<int>::iterator set_it=iset.find(1);
*set_it=11; //error: keys in a set are read-only
cout<<*set_it<<endl; //ok: can read the key

set应用:单词排出统计
void restricted_wc(ifstream& remove_file, map<string, int>& word_count){
set<string> excluded; //set to hold words we'll ignore
string remove_word;
while (remove_file>>remove_word)
excluded.insert(remove_word);
//read input and keep a count for words that aren't in the exclusing set
string word;
while(cin>>word)
//increment counter only if the word is not in excluded
if (!excluded.count(word))
++word_count[word];
}
该函数首先读取传进来的文件,该文件列出了所有被排出的单词。读入这些单词存储在一个名为excluded的set容器中。第一个while循环完成时,该set对象包含了输入文件中的所有单词。
在统计每个单词前,先检查该单词是否出现在排出集中。如果该单词出现在排出集excluded中,则调用count将返回1,否则返回0。对count的返回值做“非”运算,则当该word不在excluded中是,条件测试成功,此时,修改该单词在map中对应的值。
如果某键尚未在map容器中出现,则将该元素插入容器。所以语句++word_count[word]的效果是:如果word还没出现过,则将它插入到word_count中,并在插入元素后,将它关联的值初始化为0。然后不管是否插入了新元素,相应元素的值都加1。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: