c++ - map 是否将元素存储为 std::pair?

标签 c++ stdmap std-pair internals

std::map 是否将元素存储为 std::pair ?迭代 map 看起来像这样:

#include <map>
int main() {
    std::map<int, char> m;
    m[1] = 'A';
    m[2] = 'B';
    m[3] = 'C';

    std::map<int, char>::iterator it;
    for(it = m.begin(); it != m.end(); it++)
    {
       std::cout << "Key: "    << it->first;
       std::cout << " Value: " << it->second;
       std::cout << std::endl;
    } 
}

最佳答案

不,std::map不以对的形式存储数据,它只是以对的形式公开它。 虽然不禁止使用std::pair在底层存储中。

在典型的红黑树实现中,您至少需要两个指向存储在键和值之上的子节点的指针(可能还有一个指向父节点的指针,我真的不记得 RB 树是如何工作的,抱歉)。底层存储类型为 std::map::node_type (自 C++17 起添加),在标准中未指定(即特定于实现)。

请注意,有此子句(来自 cppreference ):

For all map containers (std::map, std::multimap, std::unordered_map, and std::unordered_multimap) whose key_type is K and mapped_type is T, the behavior of operations involving node handles are undefined if a user-defined specialization of std::pair exists for std::pair<K, T> or std::pair<const K, T>.



它建议将数据以节点句柄类型存储为 std::pair标准绝对允许(并且实现可能假设 std::pair 的行为完全符合预期)。

关于c++ - map 是否将元素存储为 std::pair?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61734265/

相关文章:

集合和对的 C++ 迭代器

c# - 为什么 C 和 C++ 中的 float / double 没有除余运算?

c++ - 使用流中的 boost binary_iarchive 序列化和反序列化

c++ - 如何在搜索中不使用 std::map 的自定义比较功能(map::find)?

c++ - std::pair 将 first 和 second 分配给语义命名的变量

C++ 对列表

c++ - <dirent.h> 的新手,试图访问目录中的数据

c++ - PerformanceCounter C++ 的 Windows 计时漂移

c++ - 根据插入时间从 std::map 中移除元素

c++ - 无法使用客户比较仿函数构造 std::map 吗?