Help me please.
Tell me how to sum each vector in a two-dimensional vector and write the result into a one-dimensional vector. On C++.
Input:
std::vector<std::vector<double>> a = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
Required Output:
b = { 9, 12 }
I found how to sum all the elements in a 2D vector, but I don't know how to sum the vectors in an existing 2D vector and write the result to a 1D vector
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<double>> a = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
std::vector<double> b;
std::vector<int> v;
int sum = 0;
for (int i = 0; i < a.size(); i++)
for (int j = 0; j < a[i].size(); j++)
{
sum += a[i][j];
}
std::cout << sum;
return 0;
}
From your example I assume that in the sums vector that you require, element in index i
, is the sum of all elements in index i
in the vectors in a
. This requires that all elements in a
have the same size.
You can do it in the following way:
Traverse the elements in a
. For each element: traverse the element (which is a vector itself) and sum element i
into the i
th bin of the output vector.
Something like:
#include <iostream>
#include <vector>
#include <assert.h>
int main()
{
std::vector<std::vector<double>> a = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
size_t num_of_sums = a[0].size(); // we assume all elements in a have the same size
std::vector<double> sums(num_of_sums);
for (auto const & v : a)
{
assert(v.size() == num_of_sums);
for (int j = 0; j < num_of_sums; j++)
{
sums[j] += v[j];
}
}
for (auto d : sums)
{
std::cout << d << ", ";
}
std::cout << std::endl;
return 0;
}
Output:
9, 12,
Note that my sums
vector contains double
s, like your input data (unlike your sum
which is an int
and seems improper to sum double
values).