2013-04-17 89 views
0

我想寫一個計算STL容器中元素總和的泛型函數。我去了解它的方式如下(t是一個容器):STL容器上的C++模板函數

template <typename T> double Sum(const T& t){ 
    typename T::reverse_iterator rit = t.rbegin(); 
    double dSum = 0.; 
    while(rit != t.rend()){ 
     dSum += (*rit); 
      ++rit; 
    } 
    return dSum; 
} 

,但我得到了一大堆錯誤。我想這個問題是關於我定義迭代器的第二行嗎?希望得到任何幫助:)

+3

像['標準:: accumulate'(http://en.cppreference.com/w/cpp/algorithm/accumulate)? –

+0

什麼錯誤?廣場至少第一個 –

回答

5

應該

typename T::const_reverse_iterator rit = t.rbegin(); 

因爲tconstrbeginconst容器回報const_reverse_iterator,不能轉化爲reverse_iterator

將更好地利用std::accumulate,而不是你自己的功能,這樣

double result = std::accumulate(c.rbegin(), c.rend(), 0.0); 
1

希望得到任何幫助:)

如果您在生產代碼中這樣做,使用改爲:這是標準的生產質量代碼,應該已經實施和測試。

如果你正在寫它作爲一個練習,考慮以下因素:

  • 定義函數接口迭代器而言,不是容器。 std :: library的最大優點之一就是將你在迭代器上應用的算法(在這種情況下爲Sum)與容器邏輯分開(你如何獲得迭代器並將它們推進)。

例如(以標準::累加),你可以把它作爲std::accumulate(t.begin(), t.end(), 0)std::accumulate(t.rbegin(), t.rend(), 0)std::accumulate(t.cbegin(), t.cend(), 0)

  • 接收值開始迭代器,並直接增加它(這將節省您需要在內部宣佈RIT;通過常量引用收到結束迭代

  • 可選:設置默認值總和(默認值應該爲零)。

+0

迭代器很好,但是例如使用cont大多數情況下,食品或範圍。 – ForEveR