gpt4 book ai didi

c++ - vector 不是 "saving values"C++

转载 作者:太空狗 更新时间:2023-10-29 23:26:14 24 4
gpt4 key购买 nike

当从 vector 中读取时,我将值放入我得到零大小。我有:

class Graph {
public:
vector<Vertex> vertices;
};

class Vertex {
public:
vector<int> adjacentVertices;
};

然后在我的加载方法中:

int vertices, edges;
cin >> vertices >> edges;
Graph mainGraph;
mainGraph.vertices.reserve(static_cast<unsigned int>(vertices));
int tmp1, tmp2;
for (int i = 0; i < edges; i++) {
cin >> tmp1 >> tmp2;
mainGraph.vertices[tmp1].adjacentVertices.push_back(tmp2);
cout << mainGraph.vertices[tmp1].adjacentVertices.size(); //PRINTS NUMBERS -> SEEMS OKAY
}

cout << mainGraph.vertices.size(); //IS ZERO???

for(const Vertex &v : mainGraph.vertices){ //CRASHES
cout << v.adjacentVertices.size();
}

我敢打赌这很愚蠢,但我错过了什么?我读到如果不需要特殊的构造函数, vector 将在使用时自行构建。

最佳答案

改变这个:

mainGraph.vertices.reserve(static_cast<unsigned int>(vertices));

为此:

mainGraph.vertices.resize(static_cast<unsigned int>(vertices));

自从 reserve()未创建 vector 的单元格,这可以通过 resize() 完成.

因此,在您的代码中,当您执行 mainGraph.vertices[tmp1] 时,您调用了未定义的行为 (UB),因为您试图访问一个对象尚未 build !

关于c++ - vector 不是 "saving values"C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52970935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com