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

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

本文关键字:指针 元素 第一个 为什么      更新时间:2023-10-16
#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 父母: 0,0 二:10,3两人的父母:4,5 三:12,7 三人的父母:4,5

即使我让一个父指向向量的第一个元素,该值最终也是 0,0。但是,其他指针指向我想要的元素。

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

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

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