c++ - 在结构内操作 vector 中的项目

标签 c++ vector struct

<分区>

试图解决这个问题时我感到很迷茫。我有自己的数据结构,我计划使用 vector 来避免跟踪可用空间和重新组织,如果我使用简单的数组,我将需要这样做。我不知道我是不是没有正确初始化还是什么,但我所做的每一项分配似乎都消失了。

这里有一些简单的代码来说明我在说什么:

#include <vector>
#include <iostream>

using namespace std;

struct node
{
    int test_int;
    bool test_bool;
};

struct file
{
    vector<node> test_file;
};

int main()
{
    file myfile;
    int myint;

    cout << "Enter number: ";
    cin >> myint;

    myfile.test_file[0].test_int = myint;

    cout << "Number entered is: " << myfile.test_file[0].test_int << endl;

    return 0;
}

所以基本上它是结构中的一个 vector 。似乎访问 vector 的正常方法似乎不起作用,因为我无法读取或向 vector 写入任何内容,但是 myfile.test_file.size() 之类的东西似乎有效(因为它们从新创建的结构中返回“0”)。尝试通过 myfile.test_file[0].test_int 直接访问索引会导致 vector subscript out of range 运行时错误,就好像它实际上不存在一样。

我没有正确初始化它吗?这对我来说似乎有点荒谬,我不明白为什么它不会那样工作。

编辑: 编辑代码以更清楚地显示我所指的行为。这会编译但给出运行时错误 vector subscript out of range

最佳答案

编辑后的版本不起作用,因为您正在访问 vector 末尾之后的元素:

    myfile.test_file[0].test_int = myint;

在执行此操作之前,您需要resize() vector ,或使用push_back() 添加一个元素:

    myfile.test_file.push_back(node());
    myfile.test_file[0].test_int = myint;

关于c++ - 在结构内操作 vector 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13549208/

相关文章:

r - 匹配两个向量的子串并创建一个组合它们的新向量

c++ - 为什么不允许在非推导上下文中使用基类定义,以及如何解决这个问题?

c++ - 如何删除 vector 的指针

c++ - 访问对象的变量减慢程序 (C++)

关于 C 中位域排序语义的澄清

c - 结构 2d 阵列 segm 故障 C

C++ - 程序已停止工作

c++ - 循环 R、G、B 值作为 HUE?

c++ - 在 QT 中链接 libCurl 给出了一个巨大的错误列表 C++

c++ - 使用boost geometry将boost段分成N个相等的段