gpt4 book ai didi

C++ 分配的指针显示意外行为

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:42 25 4
gpt4 key购买 nike

我正在用 C++ 创建点网格并将它们添加到 map 中,其中指向点的指针是值,点的 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 就不行了。

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

我真的很困惑,因为这实际上有时有效,有时无效,具体取决于我创建的点数。

谢谢!

最佳答案

您的 x 和 y 尺寸是否相同?否则,您可能会遇到索引映射被破坏的麻烦,通常它是 x + y * x_size,而不是 y。

关于C++ 分配的指针显示意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17436657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com