2017-02-27 50 views
0

我想創建一個Sum()函數來計算STL容器的總和。該函數使用模板參數的迭代器類型,並接受兩個迭代器作爲參數如下:傳遞迭代器作爲參數時沒有匹配的函數調用

template <typename T> 
double Sum(typename T::const_iterator start, typename T::const_iterator end) 
{ 
    typename T::const_iterator i3; 
    double sum2=0.0; 
    for (i3=start; i3 != end; ++i3) 
    { 
     sum2 += (i3); 
    } 
    return sum2; 
} 

,並在main()我所說的功能,如:

vector<double>::const_iterator vec_start=myvector.begin(); 
vector<double>::const_iterator vec_end=myvector.end(); 
cout<<"The sum of the vector is "<<Sum(vec_start, vec_end)<<endl; 

但它說,沒有Sum()的匹配函數調用。我讀了一些討論,這是因爲函數簽名是T,但我傳遞迭代器,並且需要在傳遞迭代器參數之前指定數據類型。

+0

是否有任何反對std :: accumulate的原因? – Skym0sh0

+0

沒有隻是一個練習容器迭代器的作業。 –

回答

0

正如您發現的討論所述,模板參數T由於non-deduced contexts無法自動推斷,因此您需要明確指定它。例如

cout << "The sum of the vector is " << Sum<vector<double>>(vec_start, vec_end) << endl; 
//          ~~~~~~~~~~~~~~~~ 

但你並不需要做的,其實,你可以改變的Sum的聲明:

template <typename I> 
double Sum(I start, I end) 
{ 
    I i3; 
    double sum2=0.0; 
    for (i3=start; i3 != end; ++i3) 
    { 
     sum2 += *i3; 
    } 
    return sum2; 
} 

I可以然後推導出它的優良最初使用它作爲

cout << "The sum of the vector is " << Sum(vec_start, vec_end) << endl; 
+0

感謝您的回覆!我現在看到邏輯:) –

+1

你不是指'* i3'而不是'(i3)'?迭代器通常被解引用來獲取它引用的值。 –

+0

是的,這是一個錯字。感謝您指出 –