我在 C++ 中创建一个点网格并将它们添加到地图中,指向该点的指针是值,点的 ID 是键。但是,指针似乎覆盖了某处。
//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;
}
}
map 实际上是一个对象成员,如下所示:
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
我真的很困惑,因为这实际上有时有效,有时无效,具体取决于我创建的点数。
谢谢!