做一个std::map中的项目永远保持在同一地址
Do items in a std::map stay at the same address forever?
>采用以下简单程序:
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;
}
因此,上面的程序缓存了一个指向地图中项目的指针。然后将更多项目添加到地图中,然后验证第一个插入的项目是否已更改位置。
当我运行它时,我有些惊讶。缓存的指针保持不变:
42 21 11 Hello world
f1 insert location has not changed
42 21 11 Hello world
我本来会假设随着地图中项目数量的增加,实现可能会移动项目——就像 std::vector 绝对一样。
所以我的问题是:只要不从地图中删除或替换插入到地图中的项目是否保证位于同一地址? 还是此实现是特定的?
是的,地图上的插入/放置操作永远不会使迭代器或对现有项目的引用无效。
26.2.6 关联容器
9insert
和emplace
成员不得影响迭代器和对容器的引用的有效性,erase
成员只能使迭代器和对已删除元素的引用无效。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 欧拉项目#8答案是大以获得有效答案
- 从链接列表c++中删除一个项目
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 既然存在危险,为什么项目要使用-I include开关
- cmake在我的项目中所需的所有静态库都不成功
- QT通过C++添加映射QML项目
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在linux上调试巨大的C++项目
- 在其他文件中创建类时在 c++ 项目中不起作用
- 使外部项目可用于find_package CMake
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- 如何维护资源管理器项目视图中当前可见的项目列表
- 做一个std::map中的项目永远保持在同一地址
- LoadLibrary 永远不会在 Visual Studio 2013 c++ 项目中返回