分类: 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
for(vector
ivec.push_back(i);
ivec.push_back(i); //duplicate copies of each number
}
//iset hold unique elements from ivec
set
cout<
cout<
添加元素
set
set1.insert("the"); //set1 now has one element
set1.insert("and"); //set1 now has two elements
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
*set_it=11; //error: keys in a set are read-only
cout<<*set_it<
set应用:单词排出统计
void restricted_wc(ifstream& remove_file, map
set
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。