map元素在内存中是固定的吗?
C++: Are map elements stationary in memory?
我们是否可以说std::map
的元素(对)是平稳的?用g++做一个快速测试,发现插入元素后,它会停留在内存中的同一位置。
定义:
struct K { ... }; // Holds an int, prints when constructed, destructed etc..
struct V { ... }; // Holds an int, prints when constructed, destructed etc..
typedef std::map<K,V> M;
M m;
调试第一次插入后的打印:
======= ADDRESS #1
DEBUG: M::const_iterator i = m.find(10)
K(10)
K.~K; value == 10
DEBUG: &*i == 0x1e6b030
DEBUG: &i->first == 0x1e6b030
DEBUG: &i->second == 0x1e6b034
调试后打印许多插入:
======= ADDRESS #2
DEBUG: M::const_iterator i = m.find(10)
K(10)
K.~K; value == 10
DEBUG: &*i == 0x1e6b030
DEBUG: &i->first == 0x1e6b030
DEBUG: &i->second == 0x1e6b034
在标准中是否有任何显式或隐式的保证元素在插入后仍保持在内存中的位置?我们有单独的键或值吗?
来自第23.1.2/8节(关联容器):
insert成员不能影响迭代器和对容器引用的有效性,也不能影响erase操作的有效性成员只能使迭代器和对已删除元素的引用失效。
所以map元素保证在内存中保持静止
相关文章:
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 擦除是否删除 stl 无序列图元素使用的堆内存
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- std::unordered_set 中的元素如何存储在C++内存中?
- 使用指针访问参数接收的结构中的元素时内存泄漏
- 存储 std::list 元素的地址;内存
- MPI_Get仅从共享内存区域读取数组的第一个元素
- C++:指针元素的向量在销毁时是否会自动释放每个指针所指向的动态内存?
- 在数组中移动一系列元素,无需额外内存
- C++释放矢量元素占用的内存时遇到的麻烦
- 从矢量中最快的擦除元素或更好地利用内存(排序基数)
- 独立于元素内存管理的向量上的函数
- 关于内存管理的QT5元素的正确用法
- 分配到STD ::向量元素会导致内存腐败
- 如何根据STL列表中的元素数量分配内存
- 为什么要指向数组或向量中最后一个元素之后的内存位置
- 我可以确保矢量元素始终在内存中吗?
- 我怎么知道基类对象的指针数组中元素的类型,它将为派生类分配内存
- std:删除元素后,字符串容量保持不变,所以它是否占用了一些内存