我正在自学如何使用迭代器创建通用函数。作为 Hello World 步骤,我编写了一个函数来获取给定范围内的平均值并返回值:
// It is the iterator to access the data, T is the type of the data.
template <class It, class T>
T mean( It begin, It end )
{
if ( begin == end ) {
throw domain_error("mean called with empty array");
}
T sum = 0;
int count = 0;
while ( begin != end ) {
sum += *begin;
++begin;
++count;
}
return sum / count;
}
我的第一个问题是:使用int
计数器可以吗,如果数据太长会溢出吗?
我从以下测试工具中调用我的函数:
template <class It, class T> T mean( It begin, It end );
int main() {
vector<int> v_int;
v_int.push_back(1);
v_int.push_back(2);
v_int.push_back(3);
v_int.push_back(4);
cout << "int mean = " << mean( v_int.begin(), v_int.begin() ) << endl;;
return 0;
}
当我编译这个我得到错误:
error: no matching function for call to ‘mean(__gnu_cxx::__normal_iterator<int*,
std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*,
std::vector<int, std::allocator<int> > >)’
谢谢!