容器
约 489 个字 44 行代码 5 张图片 预计阅读时间 2 分钟
All STL containers are templates.
有序容器
存储连续的元素
vector
std::vector (在vector头文件中)
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
并没办法从头插入元素(不支持push_front)
deque
属于双端队列,在头文件deque中,有和vector相同的接口,但deque独有push_front/pop_front
关联式容器
Associative containers organize elements by unique keys
map
std::map<K, V> maps key to values.
1 2 3 4 5 | |
map stores a collection of std::pair<const K, V>
遍历map
采取基于范围的遍历方式
1 2 3 4 5 6 | |
也可通过structured bindings 『C++17』
1 2 3 4 | |
map如何实现的? → BST(红黑树)
PS: 在使用std::map<K, V>时,K必须实现operator<,因为会根据K进行排序和查找
- e.g
int类型默认就提供了operator< - 另外定义个类,如果要进行比较类的对象,则必须进行实现,如下:
1 2 3 4 5 6 7 8 9 10 11 12 | |
set
set集合,包含在头文件set中,没有重复的元素,是map的特殊形式(即没有Values)
另外: unordered_map 和 unordered_set
unordered_map优化的map版本,有和map一样的接口- map是
std::pair的集合 - 而
unordered_mapstores a collection of n "buckets" of pairs.
- map是
为何用std::unordered_map:
- 通过保持 "load factor" 小,使得快速查找
- load factor: average number items per bucket.
- 若太大(>1.0),rehash! (可进行设置load factor, 参考
max_load_factor)
PS: unordered_set 即是unordered_map没有value,仅仅考虑key
为何unordered_map/unordered_set通常更快?
hashing + small load factor.
什么时候使用unordered_map和map
unordered_map通常更快,并且需要更多的内存- 如果key并没有要求顺序(
operator<),则可以使用unordered_map - (
unordered_map通常是更好的选择)
另外的容器
std::array:封装固定大小数组的容器std::list:a doubly linked liststd::multiset(+unordered):A set that can contain duplicatesstd::multimap(+unordered): can contain multiple values for the same key.
迭代器(Iterators)
Q: 遍历时for(const auto& elem : container) 如何工作的?
- container可为
deque/vector/map/set等
e.g. for (auto elem : s) std::cout << elem; (此处s为集合set)。等价如下形式:
1 2 3 4 | |
PS: ++it avoids making an unnecessary copy. 参考




