我有一组存储在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;
}
}
谢谢你的帮助。
最佳答案
如果您将数组的所有值初始化为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;
}