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。