标签:
引:
map容器是键-值对的集合,好比人名为键的地址和电话号码。相反的,set容器类型只是单纯的键的集合。当只想知道一个键是否存在时,使用set容器是最合适的。
除了两种例外情况,set容器支持大部分的map操作,包括下面几种:
1)第10.2节列出的所有通用的容器操作。
2)表10.3描述的构造函数。
3)表10.5描述的 insert操作。
4)表10.6描述的 count和 find操作。
5)表10.7描述的 erase操作。
两种例外包括:set不支持下标操作符,而且没有定义mapped_type类型。在set容器中,value_type不是pair类型,而是与key_type相同的类型。
一、set容器的定义和使用
与map容器一样,set容器的每个键都只对应一个元素。以一段范围的元素初始化set对象,或在set对象中插入一组元素时,对于每个键,事实上都只是添加了一个元素:
vector<int> ivec;
for (int i = 0;i != 10; ++i)
{
ivec.push_back(i);
ivec.push_back(i);
}
set<int> iset(ivec.begin(),ivec.end());
cout << "ivec: " << ivec.size() << endl;
cout << "iset: " << iset.size() << endl;
1、在set中添加元素
可以使用insert操作在set容器中添加元素:
set<string> strSet;
strSet.insert("utile");
strSet.insert("world");
for (set<string>::iterator iter = strSet.begin(); iter != strSet.end(); ++iter)
{
cout << *iter << endl;
}
另一种用法:在调用insert函数时,提供一对迭代器实参,插入其标记范围内的所有的元素。该版本的insert函数类似于形参为一对迭代器的构造函数– 对于一个键,仅仅插入一个元素:
set<int> iSet;
iSet.insert(ivec.begin(),ivec.end());
与map容器的操作一样,带有一个键参数的insert版本返回pair类型对象,包含一个迭代器和一个bool值,迭代器指向拥有该键的元素,而bool值则表明是否添加了元素。使用迭代器对的版本返回void类型。
2、从set中获取元素
set容器不提供下标操作符。为了通过键从set中获取元素,可使用find运算。如果只需简单地判断某个元素是否存在,同样可以使用count运算,返回set中该键对应的元素个数。当然,对于set容器,count的返回值只能是1(该元素存在)或0(该元素不存在):
cout << iSet.count(1) << endl;
cout << iSet.count(11) << endl;
cout << *iSet.find(1) << endl;
if (iSet.find(11) != iSet.end())
{
cout << *iSet.find(11) << endl;
}
正如不能修改map中的元素的键部分一样,set中的键也为const。在获取指向set中某元素的迭代器之后,只能对其进行读操作:
set<int>::iterator iter = iSet.find(1);
*iter = 11; //Error
cout << *iter << endl; //OK
二、创建“单词排除”集
第10.3.7节的程序从map对象 word_count中删除一个指定的单词。可将这个操作扩展为删除指定文件中所有的单词(即该文件记录的是排除集)。也即,我们的单词统计程序只对那些不在排除集中的单词进行统计:
void retricted_wc(ifstream &remove_file,map<string,int> &word_count)
{
set<string> excluded;
string remove_word;
while (remove_file >> remove_word)
{
excluded.insert(remove_word);
}
string word;
while (cin >> word)
{
if (excluded.find(word) == excluded.end())
{
word_count.insert(make_pair(word,1));
}
}
}
//原程序
void retricted_wc(ifstream &remove_file,map<string,int> &word_count)
{
set<string> excluded;
string remove_word;
while (remove_file >> remove_word)
{
excluded.insert(remove_word);
}
string word;
while (cin >> word)
{
if (!excluded.count(word))
{
++ word_count[word];
}
}
}
//P321 习题10.24
int main()
{
set<string> excluded;
ifstream inFile("input");
string excl_word;
while (inFile >> excl_word)
{
excluded.insert(excl_word);
}
string word;
while (cin >> word)
{
if (excluded.count(word))
{
cout << word << endl;
}
else
{
word.assign(word.begin(),word.end()-1);
/**也可以使用
*word.resize(word.size()-1);
*/
cout << word << endl;
}
}
}
C++ Primer 学习笔记_37_STL实践与分析(11)--set类型
标签:
原文地址:http://blog.csdn.net/selfi_xiaowen/article/details/51334699