如何在函数中提供模板数组作为参数?

时间:2019-01-22 15:36:54

标签: c++

我正在为我的C ++考试而学习,并且注意到我的答案与解决方案不同。问题在于编写一种方法,该方法可以从带有模板的数组中获得最大的double或string(按大小)。我知道,通过将数组作为参数传递,就可以指向第一个索引。 我对应该在哪里写“ const”来表示该数组没有被更改感到非常困惑。代码还包含2个荷兰语单词,“ grootste ”表示“ 最大”,“ grootte ”仅表示“ size” < / em>。 PS: max =最高

这是我的解决方案

#include <iostream>
using namespace std; 

template <typename T>
T grootste(T const [],int);
double grootte(double);

int grootte(const string&);


int main(){
    double getallen[5] = {5.5,7.7,2.2,9.8,9.9};
    string woorden[3] = {"geloof","hoop","de liefde"};

    cout << "Biggest number " << grootste(getallen,5) << "." << endl;
    cout << "Longest of 3 strings " << grootste(woorden,3) << "." << 
    endl;
    return 0;
    }

int grootte(const string &a){
    return a.size();
}
double grootte(double d){
    return d;
}

template <typename T>
T grootste (T const arr[], int lengte){
    T max=arr[0];
    for(int i=1;i<lengte;i++){
        if(grootte(arr[i])>grootte(max)){
            max = arr[i];
        }
    }
    return max;
}

这是我的课程为我提供的解决方案,不包含主要内容,其他方法相同。 我再次编写了解决方案,但现在它是学生收到的pdf的文字副本。对不起,我不知道为什么要这么做。

template < class T >
T grootste ( const T * array , int lengte ){
    T gr = array [0];
    for ( int i =1; i < lengte ; i ++) {
        if ( grootte ( gr ) < grootte ( array [i ]) ){
            gr = array [i ];
        }
    }
return gr ;
}

2 个答案:

答案 0 :(得分:1)

这些参数都是等效的:

const T p[]
T const p[]
const T *p
T const *p

选择哪一个是口味和习惯问题。

答案 1 :(得分:0)

当类型变得复杂时,我总是感到困惑。使用typedef / using语句来明确说明您的意思。

using intptr = int*; //pointer to int

void foo(const intptr arr ) {  // a const pointer to int
    arr[0] = 32;
    // arr = nullptr; //This will fail
}

using cint = const int; 

void bar(cint* arr){  // pointer to const int
    //arr[0] = 42; //This will fail
    arr = nullptr;
}

template<class T>
struct Types {
    using Tptr = T*;
    using ConstT = const T;
};

template<class T>
T grootste(typename Types<T>::constT* arr, int length) { //pointer to const T, i.e Ts in the array cannot change
    //...
}