gpt4 book ai didi

C++:将元素从 unordered_set 复制到 vector

转载 作者:行者123 更新时间:2023-11-30 02:44:02 26 4
gpt4 key购买 nike

背景:我正在为旅行商问题实现最近邻算法。我需要计算旅行的距离以及跟踪访问点的顺序。我定义了一个带有实例变量 xy 的点类,以及一个用于计算两点之间距离的函数 calcDist。我首先将所有点存储在名为 pointsstd::unordered_set 中,创建一个名为 path 的空 std::vector 存储游览路径,并将起点分配给 startPoint,并将这些传递给我的 nearestNeighbor() 函数:

void nearestNeighbor(unordered_set<Point, PointHasher> points, vector<Point> &path, Point startPoint) {
// Declare variables
unordered_set<Point, PointHasher>::iterator it;
Point currentLocation, possibleNeighbor, nearestNeighbor;
double totalDist = 0;
int pointsCount = path.capacity() - 1;

// Set the starting location
it = points.find(startPoint);
currentLocation = *it;
path[0] = currentLocation;
points.erase(currentLocation);
cout << "Start location: " << path[0].x << ", " << path[0].y << endl;

// Create the path
for (int i = 1; points.size() > 0; i++) {
double minDist = -1;
// Find the current location's nearest neighbor
for (it = points.begin(); it != points.end(); it++) {
possibleNeighbor = *it;
int currentDist = currentLocation.calcDist(possibleNeighbor);
if (minDist == -1 || currentDist < minDist) {
minDist = currentDist;
nearestNeighbor = possibleNeighbor;
}
}
// Record nearest neighbor data and prepare for the next iteration
currentLocation = nearestNeighbor;
path[i] = currentLocation;
points.erase(currentLocation);
totalDist += minDist;
cout << "Nearest neighbor: " << path[i].x << ", " << path[i].y << endl;
}
// Return to the starting location
path[pointsCount] = startPoint;
cout << "End location: " << startPoint.x << ", " << startPoint.y << endl;
cout << "Path:" << endl;
for (int i = 0; i < path.size(); i++) {
cout << path[0].x << ", " << path[0].y << endl;
}
cout << "Total distance: " << totalDist << endl;
}

问题在于,一旦程序退出外层 for 循环,path 中的所有点都会以某种方式被覆盖。要明白我的意思,这里是输出:

Start location: 3, 4
Nearest neighbor: 6, 8
Nearest neighbor: 11, 7
Nearest neighbor: 50, 8
End location: 3, 4
Path:
3, 4
3, 4
3, 4
3, 4
3, 4
Total distance: 49
Press any key to continue . . .

我认为这要么是 vector 元素的指针/地址有问题,要么是范围问题,因为问题发生在退出 for 循环之后。我什至尝试在每次迭代后打印 path[1] 以查看它何时更改,但它在整个循环中都是正确的,并且只在最后的输出中发生变化。有什么想法吗?我很难过。如果您已经走到这一步,非常感谢您抽出宝贵时间。

最佳答案

你总是输出 path[0] man 的坐标

for (int i = 0; i < path.size(); i++) {
cout << path[0].x << ", " << path[0].y << endl;
}

关于C++:将元素从 unordered_set 复制到 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655922/

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