Pointers to elements of std::vector and std::list(指向 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
这篇关于指向 std::vector 和 std::list 元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:指向 std::vector 和 std::list 元素的指针


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01