每行添加整数并将其存储在数组中

问题描述:

我正尝试使用动态分配的数组而不是向量来创建迷你函数,因为我试图弄清楚它们是如何工作的。每行添加整数并将其存储在数组中

因此,基本上,用户输入他们想要的行数,然后,他们进入一组整数/双打分隔的空间。然后,我想要函数计算每行中整数的总和,并将其分配到数组中。

例如:

3 
1 2 3 4 
3 2 2 1 //assume each line has the same # of integers (4) 
1 4 4 1 

然后,如果我实现我的功能总和会再为10,8,10

到目前为止,我有这样的:

int* total //is there a difference if I do int *total ?? 
int lines; 
std::cout << "How many lines?; 
std::cin >> lines; 
total = new int[lines]; 

for (int i=0;i<lines;i++) 
{ 
    for (int j=0;j<4;j++) 
    { 
     total[i] = ? //i'm confused how you add up each line and then put it in the array, then go onto the next array.. 
    } 
} 

如果没有任何意义,请随时提问!谢谢!

+0

'int * total'和'int * total'是相同的。 – xis

,你可能会想在内环前右设置total[i]0,然后只需使用operator+=添加任何你从std::cin流得到。

// ... 
total[i]=0; 
for (int j=0;j<4;j++) 
{ 
    int temp; 
    cin >> temp; 
    total[i] += temp; 
} 
// ... 

这可能是一个有点容易理解,如果你第一次分配的数组来存储值,然后加在一起。

IMHO可以使用2维阵列做到这一点:

所有的
int** total; 

// ... 

total = new int*[lines]; 

for(int i = 0; i < lines; ++i) 
{ 
    total[i] = new int[4]; // using magic number is not good, but who cares? 

    for(int j = 0; j < 4; ++j) 
    { 
     int tmp; 
     std::cin>>tmp; 
     total[i][j] = tmp; 
    } 
} 

// do sth on total 

for(int i = 0; i < lines; ++i) 
    delete[] total[i]; 

delete[] total; 
+0

这没有任何“添加”组件。 –

+0

@BenVoigt它应该在'//做某件我忽略的部分。 – xis

首先,需要分配一个数组的数组来存储每行的号码。例如

const size_t COLS = 4; 
size_t rows; 
std::cout << "How many lines? "; 
std::cin >> rows; 

int **number = new int *[rows]; 

for (size_t i = 0; i < rows; i++) 
{ 
    number[i] = new int[COLS]; 
} 

int *total = new int[rows]; 
// or int *total = new int[rows] {}; that do not use algorithm std::fill 

std::fill(total, total + rows, 0); 

之后,您应该输入数字并填写数字的每一行。

int* totalint *total(无论如何在你的例子)真的没有任何区别。就个人而言,我更喜欢第二个。

至于你的问题,你需要将你的总数设置为初始值(在这种情况下,你将它设置为零),然后从那里只需从cin获得值后添加到它。

With cin,既然你有空格,它会得到每个单独的数字(你知道,我假设),但是你可能应该(我会)将该数字存储到另一个变量,然后将该变量添加到该行的总数。

我认为这一切都有道理。希望能帮助到你。