C++容器(五):set类型
set类型
map容器是键-值对的集合,好比以任命为键的地址和电话号码。而set容器只是单纯的键的集合。当只想知道一个值是否存在时,使用set容器是最适合。
使用set容器必须包含set头文件:
#include <set>
set容器支持大部分map操作,包括:
- 关联容器中通用的操作。
- 三种构造函数。
insert操作。count和find操作。erase操作。
另外,还有些例外,包括:set不支持下标操作符,而且没有定义mapped_type类型。在set容器中,value_type不是pair类型,而是与key_type相同的类型。
1 set容器的定义和使用
与map一样,set容器存储的键也必须唯一,且不能修改。以一段范围内的元素初始化set对象,或在set对象中插入一组元素时,对于每个键,事实上都只添加了一个元素:
// define a vector with 20 elements, holding two copies of each number from 0 to 9
vector<int> ivec(20);
for ( int i=0; i<10; ++i )
{
ivec[2*i] = i;
ivec[2*i+1] = i;
}
// iset holds unique elements form ivec
set<int> iset( ivec.begin(), ivec.end() );
cout << ivec.size() << endl; // prints 20
cout << iset.size() << endl; // prints 10
上段代码,首先创建了一个名为ivec的int型vector容器,存储20个元素:0~9(包括9)中每个整数都出现了2次,然后用ivec中所有的元素初始化一个int型的set容器,且这个set容器仅含有10个不同的元素。
2 在set容器中添加元素
// first
set<string> mySet; // empty set
mySet.insert("the"); // mySet now has one element
mySet.insert("and"); // mySet now has two elements
// second
set<int> mySet2; // empty set
mySet2.insert( ivec.begin(), ivec.end() ); // mySet2 has 10 elements
3 从set中获取元素
set容器不提供下标操作符。为了通过键从set中获取元素,可使用find运算。如果只需简单地判断某元素是否存在,同样可以使用count运算,当然其返回值只能是1(存在)或0(不存在):
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中的键为const类型,在获得指向set中某元素的迭代器后,只能对其做读操作,而不能做写操作:
// iter refers to the element with key == 1
set<int>::iterator iter = iset.find(1);
*iter = 11; // error; keys in a set are read-only
cout << *iter << endl; // ok; can read the key
其他操作就不再累述。
参考文献:
- 《C++ Primer中文版(第四版)》,Stanley B.Lippman et al. 著, 人民邮电出版社,2013。
浙公网安备 33010602011771号