53.8k views
3 votes
Pairwise sum

Write a program called pairwise.cpp that implements the function vector sumPairWise(vector &v1, vector &v2) that returns a vector of integers whose elements are the pairwise sum of the elements from the two vectors passed as arguments. If a vector has a smaller size that the other, consider extra entries from the shorter vectors as 0. Example:

vector v1{1,2,3};
vector v2{4,5};

sumPairWise(v1, v2); // returns [5, 7, 3]
C++

1 Answer

5 votes

Final answer:

The function sum Pairwise (vector &v1, vector &v2) takes two vectors as arguments and returns a new vector where each element is the sum of the corresponding elements from the two vectors. The implementation of the function is provided in C++.

Step-by-step explanation:

The function sum Pairwise takes two vectors as arguments, v1 and v2. It returns a new vector where each element is the sum of the corresponding elements from v1 and v2. If one vector is shorter than the other, the extra entries from the shorter vector are considered as 0.

For example, if v1 is [1,2,3] and v2 is [4,5], the resulting vector would be [5, 7, 3].

Below is the implementation of the sum Pairwise function in C++:

#include <vector>

std:vector<int> sum Pairwise(std::vector<int> &v1, std:vector<int> &v2) {
std:vector<int> result.
int size = std:max(v1. size (), v2. size ()).

for (int i = 0; i < size; i++) {
int sum = (i < v1.size() ? v1[i]: 0) + (i < v2. size() ? v2[i]: 0).
result.push_back(sum).
}

return result.
}
User Andrew Samuelsen
by
7.5k points