介紹如何在 C++ 程式中使用標準程式庫的 set 儲存集合的資料。
std::set 簡介
C++ 標準函式庫中的 set 可以用來儲存集合的資料,set 裡面的元素都是唯一的,不可以重複,可以新增或刪除元素,但不可以修改元素的值。
std::set 基本範例
以下是一個最簡單的 std::set 基本使用範例,包含建立 set 集合、新增元素、檢查並列出元素等。
#include <iostream>
#include <set>
using namespace std;
int main() {
// 宣告整數 set
set<int> numSet;
// 新增元素
numSet.insert(1);
numSet.insert(6);
numSet.insert(8);
// 檢查 set 是否包含指定元素
set<int>::iterator iter;
iter = numSet.find(6);
if (iter != numSet.end()) {
cout << "Found: " << *iter << endl;
} else {
cout << "Not found." << endl;
}
// 以迴圈逐一處理 set 中的每個元素
cout << "All elements:" << endl;
for (iter = numSet.begin(); iter != numSet.end(); iter++) {
cout << *iter << endl;
}
return 0;
}
Found: 6 All elements: 1 6 8
std::set 初始化
std::set 的初始化有三種方式,除了以 insert() 函數新增元素之外,也可以直接在宣告時就以大括號初始化 set 內部的元素,或是透過 C 的陣列來初始化,以下是範例程式碼:
#include <iostream>
#include <set>
using namespace std;
int main() {
// 第一種初始化方式
set<int> numSet1;
numSet1.insert(1);
numSet1.insert(6);
numSet1.insert(8);
// 第二種初始化方式
set<int> numSet2 {1, 6, 8};
// 第三種初始化方式
int arr[] = {1, 6, 8};
set<int> numSet3(arr, arr + 3);
return 0;
}
std::set 新增、刪除元素
std::set 若要新增、刪除元素,可以使用 insert() 與 erase() 函數,以下是簡單的範例:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> numSet;
// 新增元素
numSet.insert(1);
numSet.insert(6);
numSet.insert(8);
// 刪除元素
numSet.erase(6);
// 以迴圈逐一處理 set 中的每個元素
set<int>::iterator iter;
cout << "All elements:" << endl;
for (iter = numSet.begin(); iter != numSet.end(); iter++) {
cout << *iter << endl;
}
return 0;
}
All elements: 1 8
std::set 查詢元素
若要查詢 std::set 中是否包含特定的元素,可以使用 find() 函數,若成功找到指定的元素,就會傳回對應的 iterator,而如果沒有找到,就會傳回 set::end:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> numSet {1, 6, 8};
set<int>::iterator iter;
// 在 numSet 中尋找 6 這個元素
iter = numSet.find(6);
// 如果有找到,就會傳回正確的 iterator,否則傳回 numSet.end()
if (iter != numSet.end()) {
cout << "Found: " << *iter << endl;
} else {
cout << "Not found." << endl;
}
return 0;
}
Found: 6
std::set 列出所有元素
若要列出 std::set 中的所有元素,除了以標準的 iterator 方式之外,也可以使用新的 for 迴圈寫法:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> numSet {1, 6, 8};
// 第一種列出元素的方式
cout << "All elements:" << endl;
set<int>::iterator iter;
for (iter = numSet.begin(); iter != numSet.end(); iter++) {
cout << *iter << endl;
}
// 第二種列出元素的方式
cout << "All elements:" << endl;
for (const auto &e : numSet) {
std::cout << e << endl;
}
return 0;
}
All elements: 1 6 8 All elements: 1 6 8
std::set 清空所有元素
若要清空 std::set 中的所有元素,可以呼叫 clear() 函數,而若要檢查元素的個數可用 size() 函數,另外 empty() 則可檢查 std::set 是否是空的:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> numSet {1, 6, 8};
// 清空所有元素
numSet.clear();
// 取得 set 內部元素個數
cout << "Number of elements: " << numSet.size() << endl;
// 檢查 set 是否是空的
if (numSet.empty()) {
cout << "numSet is empty." << endl;
}
return 0;
}
Number of elements: 0 numSet is empty.
