0

I have been looking at this problem for a day now but I cannot seem to find the answer. I need to use and to add all of the elements of a vector.

So far I found http://www.cplusplus.com/reference/functional/plus/ Is it possible to instead of adding 2 vector add its elements together? I can't find anything else that even comes close to doing what I want to do.

By the way I am new to the language. I don't need the code but just a hint in the right direction.

Zan Lynx
  • 51,213
  • 8
  • 77
  • 128
anonymous-dev
  • 2,243
  • 7
  • 37
  • 79

1 Answers1

3

The algorithm to preform this operation is in the numeric header, not in the algorithm header. See std::accumulate.

#include <iostream>
#include <numeric>
#include <vector>

int main()
{
    std::vector<int> data = {1, 2, 10};
    const auto result = std::accumulate(data.begin(), data.end(), 0);
    std::cout << result << std::endl;
    return 0;
}

If you insist on using functional and algorithm you could use std::for_each and std::function.

#include <algorithm>
#include <iostream>
#include <functional>
#include <vector>

int main()
{
    std::vector<int> data = {1, 2, 10};
    int result = 0;

    std::function<void(int)> sum = [&result](int value){result += value;};
    std::for_each(data.begin(), data.end(), sum);

    std::cout << result << std::endl;
    return 0;
}
François Andrieux
  • 26,465
  • 6
  • 51
  • 83