【问题标题】:c++: swapping vectors and pointer invalidation?c++:交换向量和指针失效?
【发布时间】:2012-12-27 23:54:42
【问题描述】:

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

这是一个重现我的问题的简单示例。

#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;
}

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

【问题讨论】:

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

标签: c++ pointers swap invalidation


【解决方案1】:

指针和迭代器并没有失效,而是跟随容器的内容。

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

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

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2023-03-02
    • 1970-01-01
    相关资源
    最近更新 更多