指向 std::vector 和 std::list 元素的指针
我有一个std::vector
,其中包含一些ClassA
类的元素.此外,我想使用 std::map
创建索引,该索引将一些键值映射到指向向量中包含的元素的指针.
I'm having a std::vector
with elements of some class ClassA
. Additionally I want to create an index using a std::map<key,ClassA*>
which maps some key value to pointers to elements contained in the vector.
当元素被添加到向量的末尾(不是插入)时,是否有任何保证这些指针保持有效(并指向同一个对象).即,以下代码是否正确:
Is there any guarantee that these pointers remain valid (and point to the same object) when elements are added at the end of the vector (not inserted). I.e, would the following code be correct:
std::vector<ClassA> storage;
std::map<int, ClassA*> map;
for (int i=0; i<10000; ++i) {
storage.push_back(ClassA());
map.insert(std::make_pair(storage.back().getKey(), &(storage.back()));
}
// map contains only valid pointers to the 'correct' elements of storage
如果我使用 std::list
而不是 std::vector
,情况如何?
How is the situation, if I use std::list
instead of std::vector
?
推荐答案
Vectors - 不会.因为矢量的容量永远不会缩小,所以即使删除或更改元素,也可以保证引用、指针和迭代器仍然有效,前提是它们指的是被操纵元素之前的位置.但是,插入可能会使引用、指针和迭代器失效.
Vectors - No. Because the capacity of vectors never shrinks, it is guaranteed that references, pointers, and iterators remain valid even when elements are deleted or changed, provided they refer to a position before the manipulated elements. However, insertions may invalidate references, pointers, and iterators.
列表 - 是的,插入和删除元素不会使指向其他元素的指针、引用和迭代器无效
Lists - Yes, inserting and deleting elements does not invalidate pointers, references, and iterators to other elements
相关文章