set
自動排序且元素不重複的容器
map
自動排序的鍵值對(Key-Value Pair)容器
{1, 8, 10, 17, 29}{{30, aaa}, {50, bbb}, {90, ccc}}set<資料型態> 容器名稱;set<資料型態> 容器名稱 = {};set<int> s1; // 裝整數的 set (由小到大)
set<string> s2; // 裝字串的 set(依字典序由小到大)
set<int> s3 = {30, 10, 50, 20, 40}; // 10, 20, 30, 40, 50
set<int> s4 = {30, 10, 20, 20, 30}; // 10, 20, 30#include <set>
// 由小到大 (與預設相同)
set<int, less<int>> s6;
s6.insert(10);
s6.insert(30);
s6.insert(20);
// 10, 20, 30set<資料型態, greater<資料型態>> 容器名稱;set<資料型態, less<資料型態>> 容器名稱;// 由大到小
set<int, greater<int>> s5;
s5.insert(10);
s5.insert(30);
s5.insert(20);
// 30, 20, 10set<int> s = {30, 10, 20};
for (auto x : s) {
cout << x << " ";
}
// 輸出:10 20 30for(資料型態(常用auto) 變數 : 容器)利用 for 迴圈遍歷 set 中的元素 (由小到大)
| s.insert(x) | 插入元素 x | s.begin() | 指向 第一個元素(最小值)的位置 |
|---|---|---|---|
| s.erase(x) | 刪除值為 x 的元素 | s.rbegin() | 指向 最後一個元素(最大值)的位置 |
| s.size() | 回傳元素總數 | s.end() | 指向 最後一個元素的下一個 |
| s.empty () | 檢查 set 是否為空 | s.count(x) | 計算值為 x 的數量 |
| s.clear() | 清空 set | s.find(x) | 尋找值為 x 的元素 |
map<Key型態, Value型態> 容器名稱;map<key型態, value型態> 容器名稱 = {{k1, v1}, {k2, v2}};map<string, int> m1;
map<string, int> m2 = {
{"infor", 38},
{"zsisc", 32},
{"ckcsc", 38},
{"cmioc", 32}
};// 自動排序後的順序:
{"ckcsc", 38}, // ck
{"cmioc", 32}, // cm
{"infor", 38}, // i
{"zsisc", 32} // z依照 ASCII 碼順序排列
#include <map>
// 由小到大 (與預設相同,只針對 Key 排序)
map<int, string, less<int>> m3;
m3.insert({10, "wawawa"});
m3.insert({30, "cactus"});
m3.insert({20, "shiny"});
// Key 排序為:10, 20, 30set<key型態, value型態, greater<key型態>> 容器名稱;set<key型態, value型態, less<key型態>> 容器名稱;// 由大到小 (只針對 Key 排序)
map<int, string, greater<int>> m4;
m4.insert({10, "wawawa"});
m4.insert({30, "cactus"});
m4.insert({20, "shiny"});
// Key 排序為:30, 20, 10m[key]
map<string, int> m = {
{"Math", 95},
{"Physics", 88},
};
m["Math"] = 100; // Math 的 value 改成 100
m["English"] = 85; // 插入新科目 {"English", 85}
m["Chinese"]; // 插入新的 key,value 預設為0 ({"Chinese", 0}){"Chinese", 0}
{"English", 85}
{"Math", 100}
{"Physics", 88}m.insert(k, v)
map<string, int> m = {
{"Math", 95},
{"Physics", 88},
};
m.insert({"Chemistry", 92}); // 成功插入
m.insert({"Math", 74});
// 原本就有 Math 了,不執行,Math 的 value 依舊是95{"Chemistry", 92}
{"Math", 95}
{"Physics", 88}first / second
map<string,int> m;
m={
{"zsisc",32},
{"cmioc",32},
{"ckcsc",38},
{"infor",38}
};
for (auto it : m) {
cout << it.first << " " << it.second << endl;
}ckcsc 38
cmioc 32
infor 38
zsisc 32 first / second
map<string, int> m = {
{"Physics", 90},
{"Chemistry", 85}
};
auto it = m.find("Physics");
cout << it->first << "\n"; // 答案:Physics
cout << it->second << "\n"; // 答案:90
it->first = "Biology"; // 錯誤!Key 被 const 保護,強行修改會編譯失敗
it->second = 95; // 成功!Physics 的分數被改成 95