通过模板访问 std 容器的迭代器

Access to iterators of std containers by a template

本文关键字:迭代器 std 访问      更新时间:2023-10-16

我想编写一个函数,该函数以 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 不是同一类型。

你应该使用 std::for_each 来做到这一点,而不是编写自己的函数。它将接受任何容器和任何范围的值。

如果你想编写你自己的 for range 语句:

template <typename C>
auto accumulate(const C& c) {
typename C::value_type x { };
for (auto value : c) {
x += value;
}
return x;
}
std::vector<int> my_ints{ 1, 2, 3 };
int sum = accumulate(my_ints);

正如彼得在评论中提到的,您正在尝试将实际的迭代器添加到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;
}