我在 TSP 的C++解决方案中遇到转换错误

I'm getting a conversion error in my C++ solution for TSP

本文关键字:遇到 转换 错误 解决方案 TSP C++ 我在      更新时间:2023-10-16

我正在尝试使用多维数组在C++中解决 TSP,并收到有关类型转换的错误消息。

我已经生疏了C++几年没有使用它了,所以为了重新学习,我决定尝试一些旅行推销员解决方案。我使用的第一个使用多维数组来存储随机分配的点。这部分工作正常,所以我转到距离公式。我为基本距离公式创建了一个辅助函数,该函数将 2 个数组作为其输入,其自身功能良好,然后创建了一个函数来查找完整城市数组的总距离。它接受一个双精度数组和一个表示城市总数的整数,然后遍历数组,查找每个点的距离并将它们相加。

这是变量声明和随机点分配

int numCities = 10;
double cities[numCities][2];
//Creates random(unseeded) points
for(int i = 0; i < numCities; i++){
for(int j = 0; j < 2; j++){
cities[i][j] = (rand() % 100) + 1;
}
}

这是用于调用函数的行

cout << distTotal(cities, numCities) << endl;

这是函数和辅助函数

//basic distance formula
double cityDist(double cityA[], double cityB[]){
return sqrt(pow((cityB[0]-cityA[0]), 2.0)+
pow((cityB[1]-cityA[1]), 2.0));
}
//calculate total distance of group of cities
double distTotal(double* points[], int num){
double total = 0;
for(int i = 0; i < num-1; i++){
total=total+cityDist(points[i], points[i+1]);
}
return total;
}

因此,理想情况下,这应该为我提供此处给出的基本顺序中所有点之间的总距离。但是,我目前收到以下错误:

错误:无法将参数"1"的"double (*)[2]"转换为"double**"到"double distTotal(double**, int)">

如果我没记错的话,这可能与指针有关,但老实说,我对C++指针的记忆还不够,不知道如何解决它。

任何帮助不胜感激,谢谢

当 C 数组衰减为指针时,您的声明应该double* points。如果使用 c++,您可以考虑使用std::vector<double>&作为输入。

编辑:如果您最终使用 c 数组,则必须将它们分配给堆并释放资源。

int numCities = 10;
double cities[numCities][2];

与其让一对匿名的double包含每个城市的xy位置,不如为其创建一个class/struct。这样可以更轻松地在以后扩展解决方案。例如,如果要存储城市名称及其位置:

struct position_t {
double x;
double y;
};
struct city_t {
position_t position;
std::string name;
};

然后,与其在数组中拥有固定数量的城市,不如考虑使用可以在运行时动态增长和收缩的vector

std::vector<city_t> cities;

添加了一些帮助程序函数:

#include <cmath>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
struct position_t {
position_t(double X, double Y) : x(X), y(Y) {}
double dist(const position_t& other) const {
return std::sqrt(std::pow(x - other.x, 2.) + std::pow(y - other.y, 2.));
}
// a function to print the position
friend std::ostream& operator<<(std::ostream&, const position_t&);
double x;
double y;
};
std::ostream& operator<<(std::ostream& os, const position_t& p) {
return os << '{' << p.x << ',' << p.y << '}';
}
struct city_t {
city_t(const position_t& p, const std::string_view& n) : position(p), name(n) {}
double dist(const city_t& other) const {
// this distance function just calls the function in the position_t
return position.dist(other.position);
}
// a function to print the values of the city    
friend std::ostream& operator<<(std::ostream&, const city_t&);
position_t position;
std::string name;
};
std::ostream& operator<<(std::ostream& os, const city_t& c) {
return os << c.position << ' ' << c.name;
}
int main() {
std::vector<city_t> cities = {{{10., 20.}, "Ankeborg"},
{{11., 12.}, "Gothenburg"}};
for(const auto& c : cities) {
std::cout << c << "n";
}
std::cout << "distance: " << cities[0].dist(cities[1]) << "n";
}

输出:

{10,20} Ankeborg
{11,12} Gothenburg
distance: 8.06226