我想编写一个函数,该函数需要一个std容器开始和结束,以将容器中的所有值添加到第三个参数。例如,如果我有
std::vector<int> my_ints{ 1, 2, 3 };
int sum_int = accumulate(my_ints.cbegin(), my_ints.cend(), 10); //should return 16.
我想以可以与任何std容器一起使用的方式来概括该功能。如何编写可以访问元素迭代器的模板?
template<typename It, typename T>
T accumulate(It begin, It end, T x)
{
for (It i = begin; i != end; ++i)
{
x = x + i;
}
return x;
}
这就是我目前所拥有的。但是,它不会编译,因为x和i不是同一类型。
正如Peter在评论中提到的那样,您试图将实际的迭代器添加到x
它所指向的值,而不是它指向的值。您需要取消引用迭代器以获取值:
template<typename It, typename T>
T accumulate(It begin, It end, T x) {
// there's no need create a new iterator (i) here, use the one you already have (begin):
for(; begin != end; ++begin)
x += *begin; // use * to dereference the iterator
return x;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句