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

StackOverflow https://stackoverflow.com/questions/23661099

  •  22-07-2023
  •  | 
  •  

Domanda

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?

È stato utile?

Soluzione

#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<>());

Altri suggerimenti

#include <algorithm>
#include <functional>

std::transform(vecInstA.begin(), vecInstA.end(),
               vecInstB.begin(), vecInstC.begin(), std::plus<int>());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top