指向std :: vector和std :: list元素的指针 [英] Pointers to elements of std::vector and std::list

查看:153
本文介绍了指向std :: vector和std :: list元素的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: vector 与一些类 ClassA 的元素。另外,我想使用 std :: map< key,ClassA *> 创建一个索引,它将一些键值映射到向量中包含的元素的指针。

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

推荐答案

向量 - 否。由于向量的容量从不缩小,因此即使元素被删除或更改,引用,指针和迭代器仍保持有效,前提是它们引用了操作元素之前的位置。

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元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆