我自學瞭如何使用迭代器創建通用函數。作爲世界您好一步,我寫了一個函數來取均值在給定的範圍和返回值:編寫簡單STL通用函數的問題
// 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
爲計數器OK,可以嗎溢出如果數據太長?
我打電話給我的功能從以下測試工具:
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> > >)’
謝謝!
難道你不想第二個參數是'是'是'v_int.end()'嗎?使用'int'作爲計數器可能是可以的 - 當它溢出時,你會得到一個非常巨大的負面結果。 – 2010-07-22 15:53:13
你是對的,我只是想測試我的錯誤拋出。 – recipriversexclusion 2010-07-22 16:03:28