It’s said that if swap two container’s value, the iterator will not become invalid.
so following code works fine
vector<int> v1;
v1.push_back(1);
vector<int>::iterator i = v1.begin();
vector<int> v2(v1);
v2.swap(v1);
cout<<*i<<endl; //output 1
but when I turned to a temporary container, the iterator become invalid, and the program crashed.
vector<int> v1;
v1.push_back(1);
vector<int>::iterator i = v1.begin();
vector<int>(v1).swap(v1);
cout<<*i<<endl; //i become invalid and program crashes here
This might be a stupid question, but I cann’t figure out what’s wrong.
I believe it’s because the iterator belongs to the container that you swap it with. When you swap it with a temporary, the iterator points to a member of the temporary, then the temp is destroyed and the iterator becomes invalid.
I don’t know for sure that’s how it works, but it’s the only way I could think of that iterators for a vector could stay valid after a swap (just swapping the internal pointers to the arrays, not allocating new arrays and copying, etc).