如何在具有相同第一索引的二维矩阵中添加值(c ++)

时间:2017-03-29 18:19:58

标签: c++ multidimensional-array

我有一组存储在2d矩阵中的值。我想为具有相同第一个索引的值创建单独的总计。这是一个简短的例子:

typedef int matrix [9][9];
matrix sampleMatrix;

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   for (int j = 0; j < 9; j++){
        //here's where I'm stuck
        //if i = 1, then total all values with i = 1 etc.
        if(sampleMatrix[i]){ 
        int sum = sum + sampleMatrix[i][j];
        }
        std::cout << i << " Total: " << sum << std::endl;
   }

}

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

如果用0初始化数组的所有值,那么你就可以总结每个第i个索引的所有值

matrix sampleMatrix;
for(int i=0;i<9;i++){
    for(int j=0;j<9;j++){
         sampleMatrix[i][j]=0;
    }
}

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   int sum=0;
   for (int j = 0; j < 9; j++){
          sum = sum + sampleMatrix[i][j];       
   }
   cout<<sum<<endl;
}

答案 1 :(得分:0)

构建长度为9的整数数组,如int sums [9],并用0初始化每个条目。在double for循环中,对于每个sampleMatrix [i] [j]条目,将其添加到总和的相应条目中数组,如sums [i] + = sampleMatrix [i] [j]