为什么指向矢量第一个元素的指针会丢失?
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 父母: 0,0 二:10,3两人的父母:4,5 三:12,7 三人的父母:4,5
即使我让一个父指向向量的第一个元素,该值最终也是 0,0。但是,其他指针指向我想要的元素。
std::vector
有一个capacity
。如果添加超出矢量当前容量的元素,矢量可能会决定分配更大的块,移动现有元素,然后添加新元素。这在你的案例中也一定发生过。
您可以使用reserve
提高现有矢量的容量。这不会添加额外的元素;它只是准备向量。
虽然 MSalters 正确地解释了问题的原因,以及这种特殊情况的可能解决方案,但一般做法有点不同。由于vector
可能随时重新分配,因此存储指向其元素的指针通常是个坏主意。 您可以改用索引,无论重新分配如何,索引都将有效;或者您可以考虑使用不同的数据结构,例如std::list
。std::list
元素在其一生中都保留在同一位置。
相关文章:
- 调整大小后指向元素值的指针unordered_map有效?
- 当该数组的索引中没有元素时,指针指向什么?
- 如何在基类指针向量的元素上应用重载的多态函数
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 删除指针数组 (C++) 中的元素
- 从指向结构数组的指针中提取元素
- 指向数组基址的指针而不是指向第一个元素的指针有什么优点?
- 获取指向指针的指针元素 (c++)
- 经过最后一个数组元素末尾的指针是否应该等于超过整个数组末尾的指针?
- 存储指向动态数组元素的指针
- 通过作为指向 C++ 函数的指针传递来访问 std::array 元素的正确方法是什么?
- 取消引用C++中的指针元素
- 指针数组.获取指针元素的值
- C++访问带有迭代器的向量的指针元素
- C++:指针元素的向量在销毁时是否会自动释放每个指针所指向的动态内存?
- 打印整数指针元素时的结果不同
- 访问 c++ 的矢量指针元素
- 我必须手动删除QSet的每个(指针)元素吗?
- push_back在一行中指向Vector的非指针元素