2009-08-06 131 views
0

有沒有一種簡單的方法可以做到這一點? 我被困在這裏:如何總結矩陣的列並將其存儲在C++中的向量中

#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 

請注意,矩陣可以是任何維度。

回答

1
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]; 
    } 
} 
1
// 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

這應該工作。最後,你將有資金在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
#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; 
} 
相關問題