C++:使用 for 循环创建多个数据结构

C++: creating multiple data structures using a for loop

本文关键字:数据结构 创建 循环 使用 for C++      更新时间:2023-10-16

我有一个程序,我在其中使用以下形式的记录:

// declaring a struct for each record
struct record
{
    int number;             // number of record
    vector<int> content;    // content of record    
};

在 main 中,我声明每条记录:

record batch_1;         // stores integers from 1 - 64
record batch_2;         // stores integers from 65 - 128

其中,每个批次存储数字列表中的 64 个整数(在本例中来自总共 128 个数字的列表(。我想使这个程序开放,以便该程序能够处理任何列表大小(约束它是 64 的倍数(。因此,如果列表大小为 256,我将需要四条记录(batch_1 - batch_4(。我不确定如何创建 N 条记录,但我正在寻找这样的东西(这显然不是解决方案(:

//creating the batch records
for (int i = 1; i <= (list_size / 64); i++)
{
    record batch_[i];   // each batch stores 64 integers
}

如何做到这一点,在 for 循环中声明的内容的范围是否会超出循环本身?我想数组可以满足范围要求,但我不确定如何实现它。

就像评论中的许多人建议的那样,为什么不使用C++标准库提供的可调整大小的向量:std::vector

因此,与其拥有这个:

record batch_1;         // stores integers from 1 - 64
record batch_2;         // stores integers from 65 - 128
.
.
record batch_n          // Stores integers x - y

替换为:

std::vector<record> batches;
//And to create the the batch records
for (int i = 1; i <= (list_size / 64); i++) {
    record r;
    r.number = i;
    r.content = ....;
    batches.push_back(r); 
    // You could also declare a constructor for your record struct to facilitate instantiating it.
}

你为什么不试试这个

    // code 
    vector<record> v(list_size / 64);
    // additinal code goes here

现在,您可以按如下方式访问您的数据

    (v[i].content).at(j);