我必须做一个程序,添加一个二维数组的列并返回最小的总和。这是我编写的程序,但我想知道是否有更有效的方法。主要课程是由教授给我们的。我想知道是否有办法做到这一点,而不必为每列声明一个整数,因为如果它不总是3列,谢谢。如何在C++中总结二维数组中的列?
#include <iostream>
#include <string>
using namespace std;
int smallCol(int x[][3], int row, int col){
int c1 = 0;
int c2 = 0;
int c3 = 0;
int min;
for (int r = 0; r < row; r++){
for(int c = 0; c < col; c++){
if(c==0)
c1 += x[r][c];
if(c==1)
c2 += x[r][c];
if(c==2)
c3 += x[r][c];
}
}
min = c1;
if(c2 < c1)
min = c2;
if(c3 < c2)
min = c3;
return min;
}
int main() {
int x[2][3] = {{3, 1, 4}, {1, 5, 9}};
cout << "Smallest column sum is " << smallCol (x, 2, 3) << endl;
// from the 2-d array x that has size 2 x 3, find the smallest col sum
// output will be 4 since col#0 contains 3 and 1 is smallest.
return 0;
}
需要多长时间才能支持,哦,说2d阵列与100列?这是一个相对较小的2D阵列,你知道的。 –