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?
#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<>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With