"нет подходящей функции для вызова 'Map<Flat>:: functionname"
Я пытаюсь настроить среду для путешествующих продавцов. Это моя попытка:
#include <iostream>
using namespace std;
#include<stdlib.h>
#include <cstdlib>
#include <cmath>
class Base //Allocate the memory space
{
protected:
int n;
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:
//int Path[n];
Map(int n) : Base(n)
{
int Path[n]; //Populate with random points for flat version
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, city_location); //Line 45
}
double distance(int i, int j) const //Pairwise distance function
{
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);
}
double pathdistance(double Path[],int n, double city_location) //total distance function
{
//cout<< city_location[0][1];
double total = 0;
for(int i=0; i<n-1;i++)
{
total += distance(Path[i],Path[i+1]);
}
total += distance(Path[n],Path[0]);
cout << "total distance is "<< total<<endl;
return total;
}
};
int main()
{
srand(1235);
Map<Flat> x(10);
cout << "distance between cities 3 and 7 is " << x.distance(3,7) << "\n";
}
Я получаю сообщение об ошибке:
45 error: no matching function for call to 'Map<Flat>::pathdistance(int [(((sizetype)(((ssizetype)n) + -1)) + 1)], int&, Base::Coord)'
Я знаю, что это связано с тем, как я передаю указатель, но я не могу понять, как это сделать правильно. Извиняюсь, если это выглядит уродливо для большинства из вас, но я очень плохо знаком с C++. Полегче со мной. Заранее спасибо.
3 ответа
Во-первых, функция подписи pathdistance
double pathdistance(double Path[],int n, double city_location);
не соответствует стандарту C++. double Path[]
не кошерный
Насколько ваше сообщение об ошибке идет:
45 error: no matching function for call to 'Map<Flat>::pathdistance(int [(((sizetype)(((ssizetype)n) + -1)) + 1)], int&, Base::Coord)'
Я могу сразу сказать (даже не глядя на ваш исходный код), что последний аргумент city_location
имеет тип Base::Coordinate
, но определение вашей функции требует, чтобы она была двойной.
Строка 45: вызывается функция pathdistance. Он запрашивает определенные типы параметров, которые не соответствуют аргументам, которые вы ему предоставляете:
double pathdistance(double Path[],int n, double city_location)
в конструкторе карты, где линия 45...
pathdistance попросить его третий параметр быть double
, но city_location является *Coord
или, точнее, *double[2]
то же самое для пути: функция попросила double[]
, но получил int[]
Вот небольшая программа на C, которая рассматривает проблему коммивояжера. Он основан на алгоритме ветвления и ограничения. Для создания дерева используются две структуры данных: стек и круговая очередь. Для целей тестирования матрица соединений генерируется случайным образом. Город отправления 1. Исходное решение 1-н. Но на практике использование решения, созданного с помощью эвристического алгоритма, значительно улучшило бы программу.
#include <stdio.h>
int queue[100], stack[100], alt[100], v[100];
int sp,head,tail,i,n,g,j,s,path,module,map[100][100];
int main()
{
printf("Number of cities:");
scanf( "%d",&n);
printf("Max Segment:");
scanf( "%d",&module);
printf("Seed:");
scanf( "%d",&g);
srand(g);
// Generating the sysmetric connection matrix randomly
for (i=0 ; i<n ; i++) {
for (j=i+1 ; j<n ; j++) {
map[i][j]= rand() % (module+1);
map[j][i]=map[i][j];
}
for (j=0 ; j<n ; j++) printf("%3d ",map[i][j]);
printf("\n");
}
//Start with an initial solution from city 1
for (i=0 ; i<n ; i++) {
queue[i]=i;
}
// Set route length to high value
path=module*n;
stack[0]=queue[0];
alt[0]=0;
printf("running...\n");
sp=0;
head=0;
tail=n-1;
s=0;
// Explore a branch of the factorial tree
while(1) {
while(sp<n-1 && s<path) {
sp++;
head++; if (head==n) head=0;
stack[sp]=queue[head];
s=s+map[stack[sp]][stack[sp-1]];
alt[sp]=n-sp-1;
}
// Save a better solution
if (s+map[stack[sp]][stack[0]]<path) {
path=s+map[stack[sp]][stack[0]];
for (i=0 ; i<n ; i++) v[i]=stack[i]+1;
}
// Leaving nodes when there is no more branches
while (alt[sp]==0 && sp>=0) {
tail++; if (tail==n) tail=0;
queue[tail]=stack[sp];
s=s-map[stack[sp]][stack[sp-1]];
sp--;
}
// If Bottom of stack is reached then stop
if (sp<0) break;
tail++; if (tail==n) tail=0;
queue[tail]=stack[sp];
s=s-map[stack[sp]][stack[sp-1]];
// Explore an alternate branch
alt[sp]=alt[sp]-1;
head++; if (head==n) head=0;
stack[sp]=queue[head];
s=s+map[stack[sp]][stack[sp-1]];
}
printf("best route=%d\n",path);
for (i=0 ; i<n ; i++) printf("%d ",v[i]);
printf("%d\n",stack[0]+1);
return 0;
}
Теперь давайте запустим программу для n=10.
[oldache@localhost ~]$ ./bnb
Number of cities:10
Max Segment:345
Seed:4
0 199 171 200 244 241 95 71 71 274
199 0 15 114 252 72 238 7 258 118
171 15 0 237 305 343 151 28 274 191
200 114 237 0 197 158 198 216 342 76
244 252 305 197 0 292 147 248 98 45
241 72 343 158 292 0 95 194 116 167
95 238 151 198 147 95 0 122 83 233
71 7 28 216 248 194 122 0 28 155
71 258 274 342 98 116 83 28 0 126
274 118 191 76 45 167 233 155 126 0
running...
best route=735
1 7 5 10 4 6 2 3 8 9 1