-1
我想在C++中實現一個函數,它返回任何類型數組的最小值。我現在的代碼如下所示:C++模板最小函數
main.cpp中:
#include <iostream>
#include <bits/unique_ptr.h>
#include "MathHelper.h"
using namespace std;
int main() {
std::array<int, 3> myarray = {10,20,30};
int i = MathHelper::minimum(myarray);
printf("%d\n", i);
return 0;
}
MathHelper.h:
#ifndef OPTIMIERUNG_MATHHELPER_H
#define OPTIMIERUNG_MATHHELPER_H
#include <stddef.h>
#include <array>
class MathHelper {
public:
template <typename T, size_t SIZE>
static T minimum(std::array<T, SIZE>& a);
};
#endif //OPTIMIERUNG_MATHHELPER_H
MathHelper.cpp:
#include "MathHelper.h"
template<typename T, size_t SIZE>
T MathHelper::minimum(std::array<T, SIZE> &a) {
int minimum = a[0];
if(SIZE>0){
for(size_t i=1;i<SIZE;i++){
if(a[i] < minimum){
minimum = a[i];
}
}
}
return minimum;
}
執行這個計劃成果轉化以下例外:
undefined reference to `int MathHelper::minimum<int, 3ul>(std::array<int, 3ul>&)'
[標準庫中已經有這樣的功能](http://en.cppreference.com/w/cpp/algorithm/min_element) –
至於你的問題,你在哪裏定義函數?你在哪裏打電話?您可以創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)並向我們展示? –
我必須爲大學項目做到這一點,我必須自己做。我編輯了示例以提供一個最小和完整的示例 – Finkes