#include <iostream>
using namespace std;
#include<stdlib.h>
#include <cstdlib>
#include <cmath>
class Base
{
protected:
int n; // Allocate the dynamic memory.
typedef double Coord[2];
Coord* city_location;
Base(int ncities) : n(ncities), city_location(new Coord[n]) {}
~Base() { delete [] city_location; }
};
template <class T> class Map;
struct Flat;
template <> class Map<Flat> : public Base
{
public: // Setting up the map in the flat euclidean version.
Map(int n) : Base(n)
{
double Path[n];
for (int i=0;i<n;i++)
{
city_location[i][0] = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX))*80;
city_location[i][1] = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX))*80;
Path[i] = i;
cout << "city " << i << " is at (" << city_location[i][0] << "," << city_location[i][1] << ")\n";
}
cout << "\nThe initial path is (";
for(int i=0;i<n;i++)
{
cout << Path[i]<< " ";
}
cout<< Path[0] <<")"<<endl;
//pathdistance(Path, n, distance());
}
double distance(int i, int j) const
{
double dx = city_location[i][0] - city_location[j][0];
double dy = city_location[i][1] - city_location[j][1];
return sqrt(dx*dx+dy*dy);
}
一切正常,直到这一点,但我不知道如何将距离函数/ city_location传递给总距离函数。它以Path [n]定义的顺序成对计算点。
double pathdistance(double Path,int n, double distance()) // Problem lies here, have tried with city_location and *city_location etc but can't figure it out.
{
//cout<< city_location[0][1];
double total = 0;
for(int i=0; i<n-1;i++)
{
total += distance(Path[i],Path[i+1]); \\Line 63
}
total += distance(Path[n],Path[0]);
cout << "total distance is "<< total<<endl;
return total;
}
};
int main()
{
srand(1235);
Map<Flat> x(10);
// Map<Flat> x(10);
cout << "distance between cities 3 and 7 is " << x.distance(3,7) << "\n";
}
我收到以下错误:
line 63: invalid types 'double[int]' for array subscript.
有关如何解决问题的任何想法?或者可能更简单的方法来解决我想要对总距离做些什么?感谢
答案 0 :(得分:0)
您的path
声明为double path
,表示类型为double的单值,而不是数组。
对于传递数组,您可以将其作为double *path
传递并通过索引访问元素或传递std::vector<double>
(如果您的函数不更改向量元素,则为const引用)。
double pathDistance(double *Path, unsigned int n) // first one.
double pathDistance(const std::vector<double>& Path) // second alternative.