我是新來的c + +,相當肯定錯誤是在我傳遞給函數的變量。基本上,我在double_arrays.cpp文件中定義了兩個函數 - 首先確定兩個向量之間的歐幾里德距離(以10個值的數組形式傳入,此函數效果很好)。另一個(nearestPair)是查找哪兩個向量(同樣,每個被定義爲具有10個值的數組)是距離最近的。當我在我的「main.cpp」文件中調用這個函數時,我得到了一個「沒有匹配函數叫做closestPair」的錯誤。C++「沒有匹配的函數錯誤」返回二維數組
我相當肯定,錯誤是在我傳遞給函數的值中,或者以我試圖返回它的方式(通過將值打印到控制檯)。
免責聲明 - 這如果作業:),所以對解決方案的暗示將超過歡迎!
這裏是我的文件:
main.cpp中:
#include <iostream>
#include "double_arrays.h"
int main(int argc, const char * argv[])
{
//Define test values to test vectDistance
double first[10] = {
0.595500, 0.652927, 0.606763, 0.162761, 0.980752, 0.964772, 0.319322, 0.611325, 0.012422, 0.393489
};
double second[10] = {
0.416132, 0.778858, 0.909609, 0.094812, 0.380586, 0.512309, 0.638184, 0.753504, 0.465674, 0.674607
};
//call vectDistance with test values, should equal 1.056238
std::cout << "Euclidian distance is " << vectDistance(first, second) << std::endl;
std::cout << "Should equal ~1.056238" << std::endl;
//Define test values for closestPair
double a[10] = {
0.183963, 0.933146, 0.476773, 0.086125, 0.566566, 0.728107, 0.837345, 0.885175, 0.600559, 0.142238
};
double b[10] = {
0.086523, 0.025236, 0.252289, 0.089437, 0.382081, 0.420934, 0.038498, 0.626125, 0.468158, 0.247754
};
double c[10] = {
0.969345, 0.127753, 0.736213, 0.264992, 0.518971, 0.216767, 0.390992, 0.242241, 0.516135, 0.990155
};
//create 2D array to send to closestPair
double** test = new double*[3];
test[0] = a;
test[1] = b;
test[2] = c;
//output the values of the two vectors which are closest, in Euclidian distance
std::cout << closestPair(test) << std::endl;
return 0;
}
double_arrays.cpp:
#include "double_arrays.h"
#include <iostream>
#include <vector>
#include <math.h>
double vectDistance(double first[], double second[]) {
int i = 0;
double distance = 0.0;
for (int j = 0; j < 10; ++j) {
distance += pow((first[j] - second[i]), 2);
++i;
}
return distance = pow(distance, 0.5);
}
double** closestPair(double arrays[][10]) {
double** closest = new double*[2];
closest[0] = new double[10];
closest[0] = arrays[0];
closest[1] = new double[10];
closest[1] = arrays[1];
double minDistance = vectDistance(arrays[0], arrays[1]);
for (int i = 0; i < 9; ++i){
for (int j = i + 1; j < 10; ++j) {
if (vectDistance(arrays[i], arrays[j]) < minDistance) {
minDistance = vectDistance(arrays[i], arrays[j]);
closest[0] = arrays[i];
closest[1] = arrays[j];
}
}
}
return closest;
}
最後,頭文件,header.h:
#ifndef double_arrays_double_arrays_h
#define double_arrays_double_arrays_h
double vectDistance(double first[], double second[]);
double** closestPair(double arrays[][10]);
#endif
如果你要硬編碼的大小,你應該使用'常量int'而不是有很多的如果它發生變化,10個可以修改。你也確定'new double * [3]'匹配'double arrays [] [10]'? – crashmstr 2014-09-18 15:57:52
提示:[std :: array](http://en.cppreference.com/w/cpp/container/array) – melak47 2014-09-18 15:58:32
使用向量向量? – taocp 2014-09-18 15:59:14