![](/img/trans.png)
[英]push_back getting a vector of last element by self created object
[英]push_back getting a vector of last element
我正在嘗試通過x坐標將點列表讀入向量。 但是,我一直在獲取最后一個元素的向量。 例如,如果輸入是
1 1
2 2
3 3
輸出將是
3 3
3 3
3 3
這是我的代碼:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point {
int x;
int y;
};
typedef Point* ppt;
int main()
{
//read input
int n;
cin >> n;
vector<ppt> v;
for(int i = 0; i < n; i ++){
Point p;
ppt pp = &p;
cin >> pp->x;
cin >> pp->y;
v.push_back(pp);
}
for(int i = 0; i < n; i ++){
ppt p = v.at(i);
cout << p->x << " " << p->y << endl;
}
return 0;
}
我閱讀了文檔。 如果我理解正確,vector :: push_back(pp)將復制指針並將復制的值插入v的末尾。那么問題出在哪里?
您的代碼具有未定義的行為,因為這里
ppt p = v.at(i);
cout << p->x << " " << p->y << endl;
您正在嘗試訪問一個已經被破壞的對象:
{
Point p;
ppt pp = &p;
cin >> pp->x;
cin >> pp->y;
v.push_back(pp);
} // p is destructed here, so you have a dangling pointer in the vector
而不是使用指向Point
的指針矢量,請使用std::vector<Point>
並添加對象而不是指針:
std::vector<Point> v;
//...
Point p;
cin >> p.x;
cin >> p.y;
v.push_back(p);
for(int i = 0; i < n; i ++){
Point p;
ppt pp = &p;
cin >> pp->x;
cin >> pp->y;
v.push_back(pp);
}
這段代碼是錯誤的 ,您在for循環中構造了對象Point p
,但是在for循環上運行時,銷毀了對象Point p
,但是在銷毀了Point p
對象之后,將Point p
的地址存儲到了向量中Point p
,向量中的內容無效。
您可以這樣:
for(int i = 0; i < n; i ++){
ppt pp = new Point();
cin >> pp->x;
cin >> pp->y;
v.push_back(pp);
}
在第一個循環的每次迭代中,您都在創建一個Point
類型的變量和一個指向它的指針,但是在該循環的最后,該變量被銷毀並且您的指針變成了懸空的,
在下一次迭代中,您將創建另一個變量,並在“內存中的相同位置”上執行相同的操作
最后,您的所有指針實際上都指向一個損壞的對象並稱為“拖曳”,但它們指向一個位置,並且該位置具有您最后保存的點的值。
此代碼應工作:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point {
int x;
int y;
};
typedef Point ppt;
int main()
{
//read input
int n;
cin >> n;
vector<ppt> v;
for(int i = 0; i < n; i ++){
Point p;
cin >> p.x;
cin >> p.y;
v.push_back(p);
}
for(int i = 0; i < n; i ++){
cout << v[i].x << " " << v[i].y << endl;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.