I want to write a function that takes an std container beginning and ending to add all values in the container to the third argument. For example, if I have
std::vector<int> my_ints{ 1, 2, 3 };
int sum_int = accumulate(my_ints.cbegin(), my_ints.cend(), 10); //should return 16.
I wanted to generalize this function in a way that it can work with any std containers. How can I write a template that can access to the iterators of the elements?
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;
}
This is what I have at the moment. But, it does not compile because x and i are not the same type.