c++ - 关于 C++ 结构中数组的初学者问题

标签 c++ arrays struct

我想创建一个结构并将其作为数组在另一个结构中使用。我的问题是我不知道我想分配多大的数组,我只有在函数中才能知道。我的意思是我想使用 [] 而不是预先确定的常量,例如 10000。

我认为,如果您查看我的代码,就会不言自明。你能帮我如何使这段代码工作吗?此外,如果您能告诉我我要问的主题的名称是什么(它是动态数组吗?)以及我在哪里可以找到有关该主题的文章/教程,那将对我有很大帮助。

这是我对结构中数组的错误思考方式的代码。

#include <iostream>

using namespace std;

struct keyframe {
    bool a;
    int b;
    int c;
};


struct keyframe_file {
    const int num_views;
    const int num_keyframes;
    keyframe keyframes[];
};


int main() {

    keyframe_file my_file;

    my_file.num_views = 1;
    my_file.num_keyframes = 6;

    my_file.keyframes = new keyframe[my_file.num_keyframes];

    my_file.keyframes[0].a = true;
    my_file.keyframes[0].b = 5;
    my_file.keyframes[0].c = 9;

    return 0;

}

最佳答案

使用 std::vector

struct keyframe_file {
    const int num_views;
    const int num_keyframes;
    std::vector<keyframe> keyframes;
};

int main() {
    keyframe_file frame;
    frame.keyframes.resize(...);
}

关于c++ - 关于 C++ 结构中数组的初学者问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6392843/

相关文章:

c++ - 使用 cout 打印递增的字符

python - 掩码二维 numpy 数组

堆上链表结构的 C 数组

c - 接收到结构数组

c - C : structs or arrays? 中什么更快

c++ - boost uuid + boost 字节序

c++ - 通过引用返回函数调用

c - 使字符串中的一个单词大写,C编程

javascript - 使用数组设置 jQuery 集合的值

c++ - SFINAE 检测非成员函数是否存在