结构与对象属性的交互和c ++中的std :: vector

use*_*186 2 c++ vector segmentation-fault

我遇到了这个问题,我想知道它的原因是什么.

我的代码如下:

struct node{
  bool leaf;
  std::string label;
};

//in main
std::vector<node> graph;
graph.reserve(5);
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试分配 graph[3].leaf = true;,一切都会成功.

但是,如果我尝试对对象类型执行相同操作,例如 graphA[i].label = "01";,我会遇到分段错误.

如果我将代码更改为

struct node{
  bool leaf;
  std::string * label;
};
Run Code Online (Sandbox Code Playgroud)

node在向量的每个实例中为字符串分配内存,我现在可以graphA[i]->label毫无问题地分配值.

为什么是这样?任何回复将不胜感激.

eml*_*lai 5

现在,如果我尝试分配 graph[3].leaf = true;

您正在调用未定义的行为.

graph在索引3处没有元素.事实上,它根本没有元素.你只需要向量的reserve内存,但没有添加任何元素.

您可以使用以下命令添加5个默认构造元素resize:

graph.resize(5);
Run Code Online (Sandbox Code Playgroud)