我遇到过这个问题,想知道它的原因是什么。
我的代码如下:
struct node{
bool leaf;
std::string label;
};
//in main
std::vector<node> graph;
graph.reserve(5);
现在,如果我尝试分配
graph[3].leaf = true;
,
一切顺利。
但是,如果我尝试对对象类型做同样的事情,比如
graphA[i].label = "01";
,
我遇到段错误。
如果我将代码更改为
struct node{
bool leaf;
std::string * label;
};
并在 vector 中的每个 node
实例中为字符串分配内存,我现在可以毫无问题地为 graphA[i]->label
赋值.
这是为什么?如有任何回复,我们将不胜感激。
最佳答案
Now, if i try to assign
graph[3].leaf = true;
您正在调用未定义的行为。
graph
在索引 3 处没有元素。事实上,它根本没有元素。您只为 vector 保留
d 内存,但没有向它添加任何元素。
您可以使用 resize
添加 5 个默认构造的元素:
graph.resize(5);
关于c++ - 结构与对象属性和 C++ 中的 std::vector 的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453118/