在映射中插入更多元素后,指向 QMap 中元素的指针是否仍然有效?

Will pointer to an element in QMap remain valid after inserting some more elements in the map?

本文关键字:元素 是否 指针 有效 QMap 插入 映射 指向      更新时间:2023-10-16

我有存储对象的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)方法,该方法仅在使用池时才适用。

没有充分的理由将树节点重新分配给另一个内存位置,因为通过更改叶指针值可以轻松重新定义树结构。

所以是的,指针应该随着地图的变化而保留,只要该特定键条目没有被删除。