Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values of 2 vectors [duplicate]

Tags:

c++

std

vector

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.

like image 878
MrGuy Avatar asked Feb 19 '15 13:02

MrGuy


1 Answers

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.
like image 163
Jérôme Avatar answered Nov 11 '22 23:11

Jérôme