Sim*_*ley 0 c++ containers iterator stl
我想写一个通用函数来计算STL容器中元素的总和.我的方式如下(t
是一个容器):
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;
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了很多错误.我想问题是关于我定义迭代器的第二行?不胜感激任何帮助:)
应该
typename T::const_reverse_iterator rit = t.rbegin();
Run Code Online (Sandbox Code Playgroud)
因为t
IS const
和rbegin
用于const
容器的回报const_reverse_iterator
,这是不能被转换为reverse_iterator
.
会更好地使用std::accumulate
,而不是像你自己的功能一样
double result = std::accumulate(c.rbegin(), c.rend(), 0.0);
Run Code Online (Sandbox Code Playgroud)