<分区>
试图解决这个问题时我感到很迷茫。我有自己的数据结构,我计划使用 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