qdii
qdii

Reputation: 12963

How to know when a vector’s internal array is reallocated?

I have a std::vector containing a lot of elements. As the vector is huge, I store pointers to some specific elements in another vector, to be able to access them faster. But as the vector grows, sometimes its internal container gets reallocated, causing all my pointers to become invalid.

Is there a way to know when this happens? This way I can update the pointers in the other list.

Upvotes: 3

Views: 368

Answers (4)

LeGEC
LeGEC

Reputation: 51988

You shoudldn't store pointers, you should store indexes :

i.e, instead of :

var1 = &vector[0];
var2 = &vector[13];

and access *var1, *var2

you should store :

i1 = 0;
i2 = 13;

and access vector[i1], vector[i2]


Note : you should still be careful if you use modifier methods :

  • pop_back() (which makes the last position invalid)
  • erase(i) (which shifts all the indexes greater than i)
  • etc ...

(your first method had the same caveat)

Upvotes: 6

BoBTFish
BoBTFish

Reputation: 19767

I apologise, I was plain wrong in my comment. N3337 23.3.6.3 vector capacity paragraph 5:

Remarks: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

Upvotes: 0

Jens Pohl
Jens Pohl

Reputation: 41

Maybe you should have a look at boost::container::stable_vector: http://www.boost.org/doc/libs/1_51_0/doc/html/boost/container/stable_vector.html

Upvotes: 4

Philipp
Philipp

Reputation: 69683

Instead of storing the elements in the large vector directly, you could store pointers to the individual elements. So instead of a std::vector<int> you use a std::vector<int *>. Even when the vector reallocates its content, the addresses of the data itself won't change, so other pointers to it will stay valid. This, however, requires you to create each element you enter into the vector with new and then manually delete any data which is removed.

Upvotes: 1

Related Questions