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

时间:2019-06-09 00:29:48

标签: c++

我想编写一个函数,该函数采用一个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的类型不同,因此无法编译。

2 个答案:

答案 0 :(得分:1)

您应该联系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);

答案 1 :(得分:0)

正如Peter在评论中提到的那样,您试图将实际的迭代器添加到x而不是它指向的值。您需要dereference迭代器才能获取值:

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;
}