Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to operate on two vectors and save the result to another vector [duplicate]

Tags:

c++

stl

vector<int> vecIntsA{1, 2, 3, 4};
vector<int> vecIntsB{5, 6, 7, 8};
vector<int> vecIntsC(vecIntsA.size(), 0);

for(vector<int>::size_type i = 0; i < vecIntsA.size(); ++i)
{
    vecIntsC[i] = vecIntsA[i] + vecIntsB[i];
}

Question> Is there a STL algorithm that can be used to make this calculation be done in one line?

like image 303
q0987 Avatar asked Dec 12 '25 15:12

q0987


1 Answers

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

std::vector<int> vecIntsA{1, 2, 3, 4};
std::vector<int> vecIntsB{5, 6, 7, 8};
std::vector<int> vecIntsC( vecIntsA.size(), 0)

std::transform( vecIntsA.begin(), vecIntsA.end(), 
                 vecIntsB.begin(), vecIntsC.begin(), op);

where op is binary operation, std::plus<int>() or a custom summation function like:

int sumInt( const int& a, const int& b)
{
    return a + b;
}

With C++14, you can even drop any explicit mention of the type and use just std::plus<>():

std::transform( vecIntsA.begin(), vecIntsA.end(), 
                 vecIntsB.begin(), vecIntsC.begin(), std::plus<>());
like image 100
4pie0 Avatar answered Dec 14 '25 17:12

4pie0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!