c ++:交换向量和指针失效?

lin*_*ver 3 c++ swap pointers invalidation

我似乎在交换两个向量的元素时遇到了问题.我有两个向量,x并y保存类型的对象myclass.在myclass只有一个公共的成员w.我创建指向成员的指针的矢量w的x和然后交换矢量x和y.我希望指针的向量仍然指向w成员,x但似乎并非如此.

这是一个重现我的问题的简单例子.

#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;
}
Run Code Online (Sandbox Code Playgroud)

请注意x并且y已经交换了元素,但是px仍然指向旧元素.我读到使用swap不应该使指针/迭代器无效.这是正确的还是我错过了什么?提前致谢!

Man*_*rse 5

指针和迭代器不会失效,但它们遵循容器的内容.

x交换的内容y,但迭代器和指向这些值的指针将继续指向它们(即使它们现在在其中y).

想一想,它怎么能以其他方式工作?如果交换了两个长度不等的容器,那么指向较长容器末端附近元素的指针指向较短的容器?它是如何将有可能实现swap()的O(1),如果每个容器的元素都在内存中移动,以确保指针仍然有效?