为什么指向向量第一个元素的指针丢失了?

Why does my pointer to the first element of a vector get lost?

#include <iostream>
#include <vector>
//#include <string>

struct Point {
    Point(int _x, int _y) {
        x = _x;
        y = _y;
    }

    int x;
    int y;
    Point *parent;
};

int main() {

    Point start(3, 4);
    std::vector<Point> points; 
    points.push_back(start);
    std::cout << points.back().x << "," << points.back().y << "\n";

    Point one(4, 5);
    one.parent = &points.at(0);
    //std::cout <<  "testing: " << one.parent->x << "," << one.parent->y << "\n";
    points.push_back(one);
    std::cout << "One: " << points[1].x << "," << points[1].y << "\n";
    std::cout << "One's parents: " << points[1].parent->x << "," << points[1].parent->y << "\n";

    Point two(10, 3);
    two.parent = &points.back();
    points.push_back(two);
    std::cout << "Two: " << points[2].x << "," << points[2].y << "\n";
    std::cout << "Two's parent: " << points[2].parent->x << "," << points[2].parent->y << "\n";

    Point three(12, 7);
    three.parent = &points[1];
    points.push_back(three);
    std::cout << "Three: " << points[3].x << "," << points[3].y << "\n";
    std::cout << "Three's parents: " << points[3].parent->x << "," << points[3].parent->y << "\n";


    return 1;
}

我得到以下结果: 3,4 一:4,5 一个的 parents: 0,0 二:10,3 两个 parent: 4,5 三:12,7 三 parents: 4,5

即使我将 parent 指向矢量的第一个元素,该值最终还是 0,0。但是,其他指针指向我想要的元素。

std::vector 有一个 capacity。如果添加的元素超出 vector 的当前容量,vector 可能会决定分配一个更大的块,移动现有元素,然后添加新元素。这一定也发生在你的身上。

您可以使用 reserve 增加现有向量的容量。这还不会添加额外的元素;它只是准备向量。

虽然 MSalters 正确地解释了问题的原因,以及针对这种特殊情况的可能解决方案,但一般做法有点不同。因为 vector 可能随时重新分配,所以存储指向其元素的指针通常是个坏主意。 您可以改用索引,无论重新分配如何,它都将有效;或者您可以考虑使用不同的数据结构,例如 std::liststd::list 的元素在其整个生命周期中都保持在同一位置。