set 是 STL 關聯容器,底層為紅黑樹(平衡二叉搜索樹),特點:
| 函數 | 說明 |
|---|---|
begin() | 指向首元素迭代器 |
end() | 指向末尾後迭代器 |
insert(val) | 插入元素,返回 pair<iterator,bool> |
erase(val) / erase(it) | 刪除元素/迭代器位置 |
find(val) | 查找,返回迭代器或 end() |
count(val) | 計數(0 或 1) |
size() | 元素個數 |
empty() | 是否為空 |
clear() | 清空 |
lower_bound/upper_bound | 查找首個 ≥ / > val 的迭代器 |
swap(s2) | 交換兩個 set |
set_union:並集set_intersection:交集set_difference:差集(第一個減第二個)set_symmetric_difference:對稱差集以上算法輸出需用 inserter(dest, dest.begin()) 作為輸出迭代器。
輸入兩個集合 A、B,輸出 A、B、A∪B、A∩B、A-B、SA、SB(補集相對於 A∪B)。
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
void printSet(const set<int>& s) {
cout << "{";
for (auto it = s.begin(); it != s.end(); ) {
cout << *it;
if (++it != s.end()) cout << ", ";
}
cout << "}\n";
}
int main() {
int T; cin >> T;
for (int cas = 1; cas <= T; cas++) {
set<int> A, B, C;
int n, x;
cin >> n;
while (n--) { cin >> x; A.insert(x); }
cin >> n;
while (n--) { cin >> x; B.insert(x); }
cout << "Case# " << cas << ":\n";
cout << "A = "; printSet(A);
cout << "B = "; printSet(B);
set_union(A.begin(), A.end(), B.begin(), B.end(), inserter(C, C.begin()));
cout << "A u B = "; printSet(C); C.clear();
set_intersection(A.begin(), A.end(), B.begin(), B.end(), inserter(C, C.begin()));
cout << "A n B = "; printSet(C); C.clear();
set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(C, C.begin()));
cout << "A - B = "; printSet(C); C.clear();
set_difference(B.begin(), B.end(), A.begin(), A.end(), inserter(C, C.begin()));
cout << "SA = "; printSet(C); C.clear();
set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(C, C.begin()));
cout << "SB = "; printSet(C);
}
return 0;
}
inserter(c, c.begin()) 創建一個插入迭代器,每次賦值時調用 c.insert(it, val)。適用于所有支持 insert 的容器(vector, list, set, map 等)。
set 適合需要自動去重、有序存儲、頻繁查找/插入/刪除的場景。結合