Как суммировать столбец матрицы и сохранять его в векторе в C ++ - PullRequest
0 голосов
/ 06 августа 2009

Есть ли прямой способ сделать это? Я застрял здесь:

#include <iostream>
#include <vector>
#include <cstdlib>

using std::size_t;
using std::vector;
int main()
{  
  vector<vector<int> > Matrix;

  //Create the 2x2 matrix.
  size_t rows = 2;
  size_t cols = 2;  
  // 1: set the number of rows.
   Matrix.resize(rows);


  for(size_t i = 0; i < rows; ++i)
  {
    Matrix[i].resize(cols);
  }

  // Create Matrix
  Matrix[0][0] = 1;
  Matrix[0][1] = 2;
  Matrix[1][0] = 3;
  Matrix[1][1] = 4;



  // Create Vector to store sum
  vector <int> ColSum;

  for(size_t i = 0; i < rows; ++i)
  {
    for(size_t j = 0; j < cols; ++j)
    {
      std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
      // I'm stuck here

    }
  }  

  return 0;
}

Учитывая матрицу выше:

1 2 
3 4

В конце мы надеемся напечатать результат вектора (который хранит сумму каждого столбца):

4 6

Обратите внимание, что матрица может быть любого размера.

Ответы [ 4 ]

1 голос
/ 19 марта 2011
#include <iostream.h>
#include <conio.h>
int main()
{
int A[10][10],m,n,x,y,sum=0;
//Create a Matrix A
cout << "Enter number of rows and columns in Matrix A : \n";
cin>>n>>m;
cout << "Enter elements of Matrix A : \n";
for(x=1;x<n+1;++x)
for(y=1;y<m+1;++y)
cin>>A[x][y];
//Find sum of each row
for(x=1;x<n+1;++x)
{
A[x][m+1]=0;
for(y=1;y<m+1;++y)
A[x][m+1]=A[x][m+1]+A[x][y];
}
//Find sum of each column
for(y=1;y<m+1;++y)
{
A[n+1][y]=0;
for(x=1;x<n+1;++x)
A[n+1][y]+=A[x][y];
}
cout << "\nMatrix A, Row Sum (Last Column)" << " and Column Sum (Last Row) : \n";
for(x=1;x<n+1;++x)
{
for(y=1;y<m+2;++y)
cout << A[x][y] << "     ";
cout << "\n";
}
//Print sum of each column
x=n+1;
for(y=1;y<m+1;++y)
cout << A[x][y] << "     ";
cout << "\n";
if(m==n)
{
for(x=1;x<m+1;x++)
for(y=1;y<n+1;y++)
if(x==y)
sum+=A[x][y];
else
if(y==m-(x+1))
sum+=A[x][y];
}
cout << "Sum of diagonal elements is : " << sum << endl;
getch();
return 0;
}
1 голос
/ 06 августа 2009
// Create Vector to store sum
  vector <int> ColSum;  
  ColSum.Resize(cols);
  for(size_t i = 0; i < rows; ++i)
  {
    for(size_t j = 0; j < cols; ++j)
    {
      std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
      ColSum[j] += Matrix[i][j];
    }
  }  
1 голос
/ 06 августа 2009

Это должно работать. В конце у вас будут суммы в ColSum

vector <int> ColSum;
ColSum.resize(cols);
for(size_t j = 0; j < cols; ++j)
{
    int sum = 0;
    for(size_t i = 0; i < rows; ++i)
    {
        sum += Matrix[i][j];
    }
    ColSum[j] = sum;
}  
1 голос
/ 06 августа 2009
for( size_t row = 0; row < Matrix.size(); row++ )
{
    ColSum[row] = 0;
    for( size_t column = 0; column < Matrix[row].size(); column++ )
    {
      ColSum[row] += Matrix[row][column];
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...