Please write these problems in C++ format 4. Write a function, row_sums, that pa
ID: 3626508 • Letter: P
Question
Please write these problems in C++ format4. Write a function, row_sums, that passes in a 2d vector of integers (a vector of vectors of integers) by const reference and an empty vector of integers by reference. The function should determine the sum of each of the rows in the 2d vector and place these sums in them vector of integers reference parameter. You may not assume each row has the same number of integers.
For example, if the 2d vector passed in looks like this:
2 3 5
1 8 2
0 2
9 2 3 1
then the function should fill the vector of integer reference parameter with the values (remember this vector starts off empty):
10 11 2 15
void row_sums( const vector< vector<int> > &v2d, vector<int> &sums )
Explanation / Answer
#include<iostream>
#include<vector>
using namespace std;
void row_sums( const vector< vector<int> > &v2d, vector<int> &sums )
{
for(int i=0; i<v2d.size(); i++)
for(int j=0; j<v2d.at(i).size(); j++)
sums[i] = sums[i]+v2d[i][j];
}
int main()
{
int a[]={2, 3, 5};
int b[] = {1, 8, 2};
int c[]={0, 2};
int d[]={9, 2, 3, 1};
vector<int> v1(a,a+3);
vector<int> v2(b,b+3);
vector<int> v3(c,c+2);
vector<int> v4(d,d+4);
int sums[]={0,0,0,0};
vector<int> sum(sums,sums+4);
vector<vector<int> >v;
v[0] = v1;v[1]=v2;v[2]=v3;v[3]=v4;
row_sums(v,sum);
cout << "row sums given by"<<endl;
for(int i=0; i<sum.size(); i++)
cout<<sum[i]<<" ";
return 0;
}