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。
