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.

9
  • 2
    std::accumulate Commented Jan 10, 2017 at 16:47
  • But that is not part of <algorithm> or <functional> I found that awnser to. Commented Jan 10, 2017 at 16:47
  • aahh oke because it wasn't between these cplusplus.com/reference/algorithm. Commented Jan 10, 2017 at 16:48
  • If you would be so kind to explain us why it's so important that functions of the headers <algorithm> and <functional> are used we may be able to help you furthe Commented Jan 10, 2017 at 17:03
  • @ArthurP.R. He's been working on a homework assignment for the past few days that seems to have the constraint that you can only use <functional> and <algorithm>. Commented Jan 10, 2017 at 17:20

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.