指向STL容器元素的指针 [英] Pointers to elements of STL containers
问题描述
给定一个STL容器(您也可以将 boost :: unordered_map
和 boost :: multi_index_container
纳入帐户)是不连续的,是否保证如果没有元素被移除(但是可以添加新元素),容器内的元素的存储器地址永不改变?
Given an STL container (you may also take boost::unordered_map
and boost::multi_index_container
into account) that is non-contiguous, is it guaranteed that the memory addresses of the elements inside the container never changes if no element is removed, (but new ones can be added)?
例如
class ABC { };
//
//...
//
std::list<ABC> abclist;
ABC abc;
abclist.insert(abc);
ABC * abc_ptr = &(*abclist.begin());
换句话说, abc_ptr
abc 在整个执行期间,如果我不从
abc_list $ c $中删除
abc
c>。
In other word will abc_ptr
be pointed to abc
throughout the execution, if I do not remove abc
from abc_list
.
我问这是因为我要在C ++ / Cli中包装类 ABC
我需要指向包装类中的 ABC
实例。 ABC是一个简单的类,我想要容器来处理内存。如果答案是否定的,那么我将使用 std :: list< ABC *>
。
I am asking this because I am going to wrap the class ABC
in C++/Cli, so I need pointers to the ABC
instances in the wrapper class. ABC is a simple class and I want the container to handle the memory. If the answer is no then I will use std::list<ABC*>
.
推荐答案
std :: list
, std :: set
和 std :: map
保证迭代器(包括简单指针)在添加新元素时不会失效,甚至删除。
std::list
, std::set
, and std::map
guarantee that the iterators (including simple pointers) will not be invalidated when a new element is added or even removed.
这篇关于指向STL容器元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!