在映射中插入更多元素后,指向 QMap 中元素的指针是否仍然有效?
Will pointer to an element in QMap remain valid after inserting some more elements in the map?
我有存储对象的QMap
,我想存储指向这些对象的指针以进行一些外部处理。从映射中插入/删除某些值后,指向对象的指针是否仍然有效?举例说明:
QMap <QString, QString> map;
map.insert("one", "one");
map.insert("two", "two");
map.insert("three", "three");
QString *pointer = &map["one"];
qDebug()<<*pointer;
map.insert("aaa", "aaa");
map.insert("bbb", "bbb");
qDebug()<<*pointer;
map.insert("zzz", "zzz");
map.insert("xxx", "xxx");
qDebug()<<*pointer;
是否可以保证pointer
在任意次数的插入/删除后指向完全相同的对象(当然考虑到该对象未被删除(
还是应该考虑存储指针而不是对象?
对代码进行小幅修改:
QMap <QString, QString> map;
map.insert("one", "one");
map.insert("two", "two");
map.insert("three", "three");
QString *pointer = &map["one"];
qDebug()<<pointer;
map.insert("aaa", "aaa");
map.insert("bbb", "bbb");
pointer = &map["one"];
qDebug()<<pointer;
map.insert("zzz", "zzz");
map.insert("xxx", "xxx");
pointer = &map["one"];
qDebug()<<pointer;
显示它看起来仍然有效。
QMap
元素在插入时进行排序。底层数据结构是一棵红黑树(至少在Qt5中,IIRC是Qt4中的跳过列表(。节点显然存储在堆上而不是池上,因为它没有附带reserve(space)
方法,该方法仅在使用池时才适用。
没有充分的理由将树节点重新分配给另一个内存位置,因为通过更改叶指针值可以轻松重新定义树结构。
所以是的,指针应该随着地图的变化而保留,只要该特定键条目没有被删除。
相关文章:
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 如何知道地图中的最后一个元素是否被删除?
- 检查 TinyXML 中的元素是否存在
- 使用 at() 访问 std::map 元素是否比运算符 [] 慢?
- 在迭代期间添加到 std::unordered_set(或 unordered_map)中的元素是否会在迭代期间访问?
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 通过引用访问矢量元素是否会降低C++的空间复杂性?
- 检查HTML 5视频元素是否正在获取帧
- 在c++中,如何检查一个数组的元素是否也是另一个数组中的元素
- 是否有更有效的方法来检查元素是否在给定的区间内
- 如何检查数组的 3 个元素是否具有相同的值
- 整数指针数组的元素是否可以指向整数数组?
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 写入多维矢量子级中的元素是否安全?
- 使用容器中元素的别名删除带有 std::list::remove 的元素是否正确?
- 如何确定向量的元素是否交替为符号?
- 如何查看矢量中的所有元素是否相同?
- 从标准容器中移动元素是否合法?
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?