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

本文详细介绍了集合的概念及其在编程中的应用,包括如何创建集合、添加元素、获取元素以及如何使用集合进行单词频率统计。通过实例演示了如何使用集合来高效地管理数据和执行复杂操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义

//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];

}

该函数首先读取传进来的文件,该文件列出了所有被排出的单词。读入这些单词存储在一个名为excludedset容器中。第一个while循环完成时,该set对象包含了输入文件中的所有单词。

在统计每个单词前,先检查该单词是否出现在排出集中。如果该单词出现在排出集excluded中,则调用count将返回1,否则返回0。对count的返回值做“非”运算,则当该word不在excluded中是,条件测试成功,此时,修改该单词在map中对应的值。

如果某键尚未在map容器中出现,则将该元素插入容器。所以语句++word_count[word]的效果是:如果word还没出现过,则将它插入到word_count中,并在插入元素后,将它关联的值初始化为0。然后不管是否插入了新元素,相应元素的值都加1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值