我在C++中創建一個點的網格並將它們添加到一個映射,其中指向該點的指針是該值,並且該點的ID是關鍵。但是,指針似乎覆蓋了某處。C++分配的指針顯示意外的行爲
//At first, create them like an array
HPoint** points = new HPoint*[x_values.size() * y_values.size()];
//First x, then y
int y_count = y_values.size();
for(int x_index = 0; x_index < x_values.size(); x_index++) {
for(int y_index = 0; y_index < y_values.size(); y_index++) {
HPoint* newPoint = new HPoint();
newPoint->setX(x_values[x_index]);
newPoint->setY(y_values[y_index]);
allPoints.insert(std::pair<int, HPoint*>(newPoint->getId(), newPoint));
//This is the check within the loop
refreshSegments();
//Also insert into a grid, for better access
points[x_index + y_count * y_index] = newPoint;
//Assign connection
if(y_index > 0) {
HPoint* otherPoint = points[x_index + y_count * (y_index-1)];
Segment* newSegment = new Segment(otherPoint, newPoint);
allSegments.push_back(newSegment);
}
if(x_index > 0) {
HPoint* otherPoint = points[x_index -1 + y_count * y_index];
Segment* newSegment = new Segment(otherPoint, newPoint);
allSegments.push_back(newSegment);
}
}
}
std::cout << "Out of the loop!: " << allPoints.size() << std::endl;
refreshSegments();
我使用refreshSegments()函數來檢查,如果有一些的ID超出範圍:
void MeshGeneration::refreshSegments()
{
//refresh points too
for(std::map<int, HPoint*>::iterator it = allPoints.begin(); it!=allPoints.end();) {
std::cout << it->second << " " << it->second->getId() << std::endl;
if(it->second->getId() > it->second->getCounter() || it->second->getId() < 0) {
std::stringstream ss;
ss << "Unexpected Id: " << it->second->getId() << " " << it->second;
throw std::runtime_error(ss.str());
}
++it;
}
}
地圖實際上是一個對象部件和看起來像這樣:
std::map<int, HPoint*> allPoints;
輸出看起來像這樣。很明顯,當循環中調用檢查時,指針0xc61138沒有問題,但從循環外部調用時卻不好。
0xc61138 0
0xc61188 1
0xc61240 2
0xc61348 3
0xc61438 4
0xc61500 5
0xc61620 6
0xc63030 7
0xc63118 8
0xc63200 9
0xc63388 10
0xc634e8 11
0xc63648 12
0xc63778 13
0xc63928 14
0xc63a60 15
0xc63b98 16
0xc63c60 17
0xc63d70 18
0xc63ea8 19
0xc63fe8 20
0xc64120 21
0xc63868 22
0xc64428 23
0xc64588 24
0xc64678 25
0xc64788 26
0xc648c0 27
0xc649f8 28
0xc64b30 29
0xc64c68 30
0xc64da0 31
0xc64f00 32
0xc64ff0 33
0xc65100 34
0xc65238 35
0xc65370 36
0xc654a8 37
0xc655e0 38
0xc64258 39
0xc65978 40
0xc65a68 41
0xc65b78 42
0xc65cb0 43
0xc65de8 44
0xc65f20 45
0xc66058 46
0xc66190 47
0xc662f0 48
0xc663e0 49
0xc664f0 50
0xc66628 51
0xc66760 52
0xc66898 53
0xc669d0 54
0xc66b08 55
Out of the loop!: 56
0xc61138 13003528
我真的很困惑,因爲這實際上有時有效,有時不會,這取決於我創建的點數。
謝謝!
順便說一句,我在析構函數中添加了一個cout,這樣我就可以看到HPoint是否被破壞了。這似乎並非如此。 – Tib51
如果您還顯示'it-> first'?這將表明getId()是否起作用,因爲它被用作關鍵字。 – paddy
我想我找到了一個解決方案...它看起來像我的索引是錯誤的。而不是做 points [x_index + y_count * y_index] = newPoint; 我該做的 points [x_index + x_count * y_index] = newPoint; 對不起,我在看之前非常努力...... – Tib51