C++ c++;:交换向量和指针无效?

C++ c++;:交换向量和指针无效?,c++,pointers,swap,invalidation,C++,Pointers,Swap,Invalidation,我似乎在交换两个向量的元素时遇到了问题。我有两个向量,x和y,它们保存类型为myclass的对象。myclass只有一个公共成员w。我创建一个指向x的w成员的指针向量,然后交换向量x和y。我希望指针向量仍然指向x的w成员,但情况似乎并非如此 这里有一个简单的例子来重现我的问题 #include <iostream> #include <vector> using namespace std; struct myclass { double w; }; in

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

这里有一个简单的例子来重现我的问题

#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;
}
#包括
#包括
使用名称空间std;
结构myclass
{
双w;
};
int main()
{
向量x(10);
对于(inti=0;i!=10;i++)x[i].w=i;

对于(auto el:x)std::cout,指针和迭代器不会失效,但它们遵循容器的内容

x
的内容被交换为
y
,但指向这些值的迭代器和指针将一直指向它们(即使它们现在位于
y


想想看,它是如何以任何其他方式工作的?如果交换两个长度不等的容器,那么指向较长容器末尾附近元素的指针会指向较短容器中的哪些元素?如何在
O(1)中实现
swap()
如果必须在内存中移动每个容器的元素以确保指针保持有效?

文档说它们不会失效,而且它们没有失效-这意味着它们仍然指向它们一直指向的地方。