イテレータを使用してジェネリック関数を作成する方法を独学で学んでいます。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> > >)’
ありがとう!