在结构中操纵向量中的项
manipulating items in a vector within a struct
试图弄清楚这一点我感到很失落。我有自己的数据结构,我计划使用向量来避免跟踪空闲空间和重组,如果我使用简单的数组,我需要这样做。我不知道我是不是没有正确初始化,但我所做的每一项任务似乎都烟消云散。
这里有一些简单的代码来说明我所说的:
#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;
}
所以基本上它是一个结构中的向量。访问向量的普通方法似乎不起作用,比如在中,我不能对向量读写任何东西,但像myfile.test_file.size()
这样的东西似乎起作用(比如它们从新创建的结构中返回"0")。尝试通过myfile.test_file[0].test_int
直接访问索引会导致vector subscript out of range
的运行时错误,就好像它实际上不存在一样。
我没有正确初始化它吗?这在我看来有点可笑,我不明白为什么它不会那样工作。
编辑:经过编辑的代码可以更清楚地显示我所指的行为。这会编译,但会产生运行时错误vector subscript out of range
编辑后的版本不起作用,因为您访问的元素超过了向量的末尾:
myfile.test_file[0].test_int = myint;
在执行此操作之前,您需要resize()
矢量,或者使用push_back()
:添加元素
myfile.test_file.push_back(node());
myfile.test_file[0].test_int = myint;
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 如何在C 中操纵向量
- 在结构中操纵向量中的项
- 操纵对STL容器(例如向量)中元素的引用