Sum values of 2 vectors

30,747

You can use std::transform and std::plus<int>()

std::vector<int> a;//looks like this: 2,0,1,5,0
std::vector<int> b;//looks like this: 0,0,1,3,5

// std::plus adds together its two arguments:
std::transform (a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
// a = 2,0,2,8,5

This form of std::transform takes 5 arguments:

  • Two first are input iterators to the initial and final positions of the first sequence.
  • The third is an input iterator to the initial position of the second range.
  • The fourth is an output iterator of the initial position of the range where the operation results are stored.
  • The last argument is a binary function that accepts two elements as argument (one of each of the two sequences), and returns some result value convertible to the type pointed by OutputIterator.
Share:
30,747
MrGuy
Author by

MrGuy

Java &amp; Android developer

Updated on February 20, 2020

Comments

  • MrGuy
    MrGuy about 4 years

    Is there any implemented method in the C++ library which allows you to sum the values of two vectors (of the same size and type of course)?
    For example:

    std::vector<int> a;//looks like this: 2,0,1,5,0
    std::vector<int> b;//looks like this: 0,0,1,3,5
    

    Now then adding their values together should look like this:

    //2,0,2,8,5
    

    The answer I'm expecting is either "No there isn't" or "yes" + method.