Reputation: 3823
I seem to be having a problem with swapping the elements of two vectors. I have two vectors, x
and y
that hold objects of type myclass
. The myclass
has only one public member w
. I create a vector of pointers pointing to the members w
of x
and then swap the vectors x
and y
. I would expect the vector of pointers to still point to the w
members of x
but this does not seem to be the case.
Here is a trivial example to reproduce my problem.
#include <iostream>
#include <vector>
using namespace std;
struct myclass
{
double w;
};
int main()
{
vector<myclass> x(10);
for(int i=0; i!=10; i++) x[i].w = i;
for(auto el : x) std::cout << el.w << std::endl; /* prints i */
std::cout << std::endl;
vector<double *> px(10);
for(int i=0; i!=10; i++) px[i] = &x[i].w;
for(auto el : px) std::cout << *el << std::endl; /* prints i */
std::cout << std::endl;
vector<myclass> y(10);
for(int i=0; i!=10; i++) y[i].w = 2*i;
for(auto el : y) std::cout << el.w << std::endl; /* prints 2*i */
std::cout << std::endl;
y.swap(x);
for(auto &el : x) std::cout << &el.w << " " << el.w << std::endl; /* prints 2*i as it should */
std::cout << std::endl;
for(auto &el : px) std::cout << el << " " << *el << std::endl; /* should print 2*i, but prints i */
std::cout << std::endl;
}
Notice that x
and y
have swapped elements but px
stills points to the old elements. I read that using swap
is not supposed to invalidate pointers/iterators. Is this correct or am I missing something?
Thanks in advance!
Upvotes: 3
Views: 685
Reputation: 40633
The pointers and iterators are not invalidated, but they follow the contents of the container.
The contents of x
are swapped into y
, but iterators and pointers to these values will keep pointing at them (even though they are now in y
).
Think about it, how could it work in any other way? If two containers of unequal length were swapped, what would pointers to elements near the end of the longer container point to in the shorter container? How would it be possible to implement swap()
in O(1)
if the elements of each container had to be moved in memory to ensure that pointers remained valid?
Upvotes: 5