我参加了 C ++ Primer 6th :
通过提供
average_list()
功能完成程序。它应该是一个 模板函数,使用type参数指定类型initialized_list
模板用作函数参数,也用于给函数返回类型。
我不知道它
以下是短程序的一部分:
int main() {
using namespace std;
// list of double deduced from list contents
auto q = average_list({15.4, 10.7, 9.0});
cout << q << endl;
// list of int deduced from list contents
cout << average_list({20, 30, 19, 17, 45, 38} ) << endl;
// forced list of double
auto ad = average_list<double>({'A', 70, 65.33});
cout << ad << endl;
}
答案 0 :(得分:1)
你可能会这样:
#include <iterator>
#include <numeric>
#include <iostream>
template <typename T>
auto average_list(const std::initializer_list<T> &v) -> decltype(T() / 1.0)
{
return std::accumulate(std::begin(v), std::end(v), T()) / static_cast<float>(std::distance(std::begin(v), std::end(v)));
}
该行
auto average_list(const std::initializer_list<T> &v) -> decltype(T() / 1.0)
表示average_list
对某些类型T
采用初始化列表const引用,并返回通过将T
除以浮点数获得的类型。
函数的主体只使用numeric
等的STL函数。
答案 1 :(得分:0)
您需要编写参数化函数,它使用模板,它使变量的类型成为参数。
然后,编译器可以推导出传递值的类型,专门你的函数来处理传递的类型。
根据名称average_list()
判断,函数应该返回传递的参数的平均值,因此您需要编写代码来创建它,从一种类型开始,例如int
和然后只需使用模板参数替换int
。执行此操作的语法是:
template <typename T> // prefix in front of the function
示例:下面的函数仅处理int
int sum_vector(const std::vector<int>& v) {
int sum = 0;
for (size_t i = 0; i < v.size(); ++i){
// accumulate sum
sum += v[i];
}
return sum;
}
制作上述函数参数的类型,你可以写:
template<typename T> T sum_vector(const std::vector<T>& v) {
T sum = 0;
for (size_t i = 0; i < v.size(); ++i){
// accumulate sum
sum += v[i];
}
return sum;
}
然后根据作为参数传递的T
的类型确定vector
,即如果向量的类型是int
,则T
&#34;变为&#34; 1 int
,如果double
则T
&#34;变为&#34 ; 一个double
。
1。编译器会为您提供类型为int
的函数实例化。