1

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
  • 53,022
  • 10
  • 79
  • 131
anonymous-dev
  • 2,897
  • 9
  • 48
  • 112

1 Answers1

4

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
  • 28,148
  • 6
  • 56
  • 87
  • 1
    Depending on what type You would like to return by accumulate function You should use either 0 for integer or 0.0 for double result value. – Albi93 Mar 19 '23 at 20:12