| 容器 |
存什么 |
是否允许重复 key |
是否有序 |
常见底层实现 |
查找复杂度 |
set |
key |
❌ |
✅ |
红黑树 |
(O(\log n)) |
multiset |
key |
✅ |
✅ |
红黑树 |
(O(\log n)) |
unordered_set |
key |
❌ |
❌ |
哈希表 |
平均 (O(1)) |
map |
key -> value |
❌ |
✅ 按 key |
红黑树 |
(O(\log n)) |
unordered_map |
key -> value |
❌ |
❌ |
哈希表 |
平均 (O(1)) |
便利方式
// set
for (auto x : s) {
cout << x << '\n';
}
// unordered_set
for (auto x : s) {
cout << x << '\n';
}
// map
for (auto p : mp) {
cout << p.first << ' ' << p.second << '\n';
}
// unordered_map
for (auto p : mp) {
cout << p.first << ' ' << p.second << '\n';
}
// set
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << '\n';
}
// unordered_set
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << '\n';
}
// map
for (auto it = mp.begin(); it != mp.end(); ++it) {
cout << it->first << ' ' << it->second << '\n';
}
// unordered_map
for (auto it = mp.begin(); it != mp.end(); ++it) {
cout << it->first << ' ' << it->second << '\n';
}
for (auto it = mp.begin(); it != mp.end(); ++it) {
cout << it->second.mx << '\n';
}
| 操作 |
含义 |
时间复杂度 |
a[i]、a.test(i) |
读取一位 |
(O(1)) |
a[i]=v |
修改一位 |
(O(1)) |
a.set(i)、a.reset(i)、a.flip(i) |
单位置 1、清零、翻转 |
(O(1)) |
a.size() |
返回位数 (N) |
(O(1)) |
a.set()、a.reset()、a.flip() |
整体置 1、清零、翻转 |
(O(B)) |
a & b、a | b、a ^ b、~a |
整体位运算 |
(O(B)) |
a &= b、a |= b、a ^= b |
原地位运算 |
(O(B)) |
a << k、a >> k、a <<= k、a >>= k |
整体移位 |
(O(B)) |
a.count() |
统计 1 的个数 |
(O(B)) |
a.any()、a.none()、a.all() |
判断存在 1、全 0、全 1 |
(O(B)),可能提前结束 |
a == b、a != b |
比较是否相等 |
(O(B)),可能提前结束 |
a = b、拷贝构造 |
复制整个 bitset |
(O(B)) |
a.to_ulong()、a.to_ullong() |
转整数,含高位溢出检查 |
(O(B)) |
从 string 构造、to_string()、输入输出 |
按字符转换 |
(O(N)) |
a._Find_first() |
找下标最小的 1,GCC 扩展 |
(O(B)) |
a._Find_next(i) |
找下标严格大于 (i) 的下一个 1,GCC 扩展 |
(O(B)) |