#include<iostream>
#include<initializer_list>
#include<algorithm>
using namespace std;
// create a template function, which will add all elements together
// initializer_list is container
template<typename T>
T average_list(initializer_list<T> il)
{
T tot = 0;// sum of elements in initializer_list
T ct = 0;// count of elements in initializer_list
for (auto iter = il.begin(); iter != il.end(); iter++)
{
tot += *iter;
ct++;
}
// another approach
//for_each(il.begin(), il.end(), [&](T x) ->T {ct++; return tot += x; });// add each element to tot
return tot / ct;
}
int main()
{
// 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;
cin.get();
return 0;
}
C++ Premier Plus 6th edition - Programming excercise - Chapter18 - 1
最新推荐文章于 2024-10-17 14:06:21 发布