Chinaunix首页 | 论坛 | 博客
  • 博客访问: 160061
  • 博文数量: 30
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 290
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-25 19:05
文章分类

全部博文(30)

文章存档

2009年(3)

2008年(27)

我的朋友

分类: C/C++

2008-11-27 16:41:39

定义

//define a vector with 20 elements, holding two copies of each number from 0 to 9

vector ivec;

for(vector::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 iset(ivec.begin(), ivec.end());

cout< //print 20

cout< //print 10

 

添加元素

set set1;    //empty set

set1.insert("the");   //set1 now has one element

set1.insert("and");   //set1 now has two elements

 

set 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::iterator set_it=iset.find(1);

*set_it=11;         //error: keys in a set are read-only

cout<<*set_it<//ok: can read the key

 

 

set应用:单词排出统计

void restricted_wc(ifstream& remove_file, map& word_count){

       set 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

阅读(13592) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-12-16 17:25:56

set set2; //empty set 兄弟,这里出错了哟,怕应该是 set set2;哦