Vladimir Yanakiev Vladimir Yanakiev - 2 months ago 9
C++ Question

Setting vector of int pointers, to point to elements of vector of int

I try to set vector of pointers to int to elements of another vector

vector<int> vecInt;
vector<int*> vecPInt;
int main()
{
vecInt.push_back(1);
vecPInt.push_back(&vecInt[0]);
vecInt.push_back(1);
vecPInt.push_back(&vecInt[1]);
for(auto v:vecInt)
{
cout<<v<<"\n";
}
for(auto v:vecPInt)
{
cout<<*v<<"\n";
}


}

but the result is

1

1

11717664

1

There are another way to do this. But why in this case this is the behaviour?

Answer

The second time you push back an element into the vector vecInt, the capacity of the vector changes. New area of twice the size is allocated and hence the old pointer starts pointing to something else. Basically, whenever the size of the vector reaches its capacity, reallocation of the vector has to happen and it invalidates all pointers referring to the elements in the sequence.
Have a look at When does a std::vector reallocate its memory array?