Adding all elements in a vector with C++
Adding the elements of a vector with a for loop looks
#include <vector>
int sum(std::vector<int> nums) {
// your code here
int sum = 0;
for (int i = 0; i < nums.size(); i++)
{
sum += nums[i];
}
return sum;
}
However, there's a way to do it with a one-liner by using the accumulate function from the numeric library.
#include <vector>
#include <numeric>
int sum(std::vector<int> nums) {
return std::accumulate(nums.begin(), nums.end(), 0);
}
According to the official documentation, accumulate takes in the first and last iterators as the first two arguments. We then have to specify the initial index which we want to perform our summation.
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init);