C++ STL: Set

  1. 1. 簡介
  2. 2. 標頭檔
  3. 3. 宣告
  4. 4. 常用操作
  5. 5. 範例

集合

簡介

按照特定順序存儲元素,其元素不重覆。

標頭檔

1
#include <set>

宣告

1
set<type> myset

type 可為 int, char, string…,myset可為任意名字。

常用操作

函數 描述
insert() 插入指定元素
erase() 刪除指定元素
clear() 刪除所有元素
count() 回傳元素是否存在
find() 回傳指向該元素的迭代器
empty() 回傳是否為空
size() 回傳有幾個元素

範例

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <set>
using namespace std;

int main(){
set<int> myset;
myset.insert(4); //插入元素
myset.insert(8);
myset.insert(7);
myset.insert(2);
cout << "目前元素個數為 " << myset.size() << "\n";
myset.erase(2); //刪除指定元素
cout << "此元素是否存在 " << myset.count(2) << "\n";
myset.insert(6), myset.insert(3);
myset.insert(8); //8已經存在,此行沒效果
for(auto it = myset.begin(); it != myset.end(); ++it){ //使用迭代器遍歷
cout << *it << " ";
}
cout << "\n";
myset.clear(); //刪除所有元素
cout << "是否為空 " << myset.empty() << "\n";

return 0;
}
輸出

目前元素個數為 4
此元素是否存在 0
3 4 6 7 8
是否為空 1

資料來源:cplusplus.com