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

Adding integers per line and storing it in array

本文关键字:存储 数组 添加 整数      更新时间:2023-10-16

我正在尝试使用动态分配的数组而不是向量创建一个迷你函数,因为我试图弄清楚它们是如何工作的。

所以基本上,用户输入他们想要的行数,然后,他们输入一组由空格分隔的整数/双精度。然后,我希望函数计算每行整数的总和,并将其分配到数组中。

例如:

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..
     }
 }

如果有什么不合理的地方,请随时询问!谢谢!

您可能希望将total[i]设置为在内部循环之前0,然后使用operator+=添加从std::cin流中获得的任何内容。

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

如果您首先分配了一个数组来存储值,然后将它们加在一起,可能会更容易理解。

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

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

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

我认为这一切都是有道理的。希望对您有所帮助。

恕我直言,您可以使用二维数组来做到这一点:

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;