c++ - std::map 中的项目是否永远保持在同一个地址?

标签 c++ std stdmap

采用以下简单程序:

struct Foo
{
    int x;
    int y;
    int z;
    string s;
};

int main()
{
    Foo f1 = { 42,21,11, "Hello world" };
    std::map<int, Foo> foomap;

    foomap[400] = f1;
    Foo* ptr = &foomap[400]; // cache a pointer to the element we just inserted.

    cout << ptr->x << " " << ptr->y << " " << ptr->z << " " << ptr->s << std::endl;

    // fill the map up with a bunch of other random items at random indices   
    for (int x = 0; x < 10000; x++)
    {
        int i = rand();
        Foo f = { rand(), rand(), rand(), "Another string" };

        if (foomap.find(i) == foomap.end())
        {
            foomap[i] = f;
        }
    }

    Foo* ptr2 = &foomap[400];

    cout << "f1 insert location has " << ((ptr == ptr2) ? "not changed" : "changed") << std::endl;
    cout << ptr->x << " " << ptr->y << " " << ptr->z << " " << ptr->s << std::endl;

    return 0;
}

所以上面的程序缓存了一个指向 map 中某个项目的指针。然后将更多项目添加到 map 中,然后验证第一个插入的项目是否已更改位置。

当我运行它时,我有些惊讶。缓存的指针保持不变:

42 21 11 Hello world
f1 insert location has not changed
42 21 11 Hello world

我会假设随着 map 中项目数量的增长,实现可能会移动项目 - 就像 std::vector 所做的那样。

所以我的问题是:只要不从 map 中删除或替换,插入到 map 中的项目是否保证位于同一地址?或者这个实现是特定的?

最佳答案

是的, map 上的插入/放置操作永远不会使迭代器或对现有项目的引用无效。

26.2.6 Associative containers [associative.reqmts]
9 The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

关于c++ - std::map 中的项目是否永远保持在同一个地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392170/

相关文章:

c++ - 相等性的预处理器测试总是评估为真

c++ - 如何完全管理 std 容器(如 map)的堆内存分配?

c++ - 如何从 std::map 中的 std::pair 的 std::vector 获取输入?

c++ - Cocos2dx 动画(不使用过时的方法)

c++ - 在 C++ 中嵌入 Guile 的问题

c++ - 柠檬在 C++ 中生成的解析器的段错误

c++ - 为 C++ 字符串中的特殊符号 (") 赋予字面意义的有效 C++ 方法

c++ - 在 google::dense_hash_map 中存储 std::vectors 使其变慢

c++ - 如何重新组合 map 并将元素插入新 map ?

c++ - 跨多个对象使用 map