1. 简述
std::map、std::multimap 和 std::unordered_map 是 C++ 标准模板库(STL)中的三种关联容器,它们提供了存储键值对(pair)的方式,并允许通过键来快速检索值。这三者之间的主要区别在于它们的内部数据结构和对元素的排序方式。
2. std::map的特点
有序性:std::map 中的元素按照键的顺序存储,因此可以高效地进行中序遍历。
唯一性:每个键在 std::map 中都是唯一的,不允许重复的键存在。
性能:std::map 提供了对元素的高效查找、插入和删除操作,时间复杂度通常为 O(log n)。
内存消耗:由于使用平衡二叉搜索树,std::map 相比于 std::unordered_map 可能会有更高的内存消耗。
可预测性:由于元素的有序性,std::map 在迭代时提供了可预测的顺序,这在某些算法中非常有用。
3. std::map构造及其用法
(1)构造map
首先需要引用头文件:#include <map>
默认构造:
std::map<int, std::string> amap;
使用初始化列表进行构造:
std::map<int, std::string> myMap = {
{1, "one"},
{2, "two"},
{3, "three"}
};
复制构造:
std::map<int, std::string> myMap


2089

被折叠的 条评论
为什么被折叠?



