有什么方法可以将元素添加到列表中,如图所示?
Is there any way I can add elements to list like shown?
我正在尝试将元素添加到向量中的列表中。addEdge 方法中发生此错误,因为它无法访问所需的容器(分段错误(。该图是一个向量,其中每个容器都包含连接到它的顶点列表(以及该边的权重,在本例中为 0(。
Graph(int n, bool directed)
{
this->n = n;
graph.reserve(n);
this->directed = directed;
this->m = 0;
}
void addEdge(int x, int y)
{
graph[x - 1].push_back({y - 1, 0});
if (!directed)
graph[y - 1].push_back({x - 1, 0});
m++;
}
M 是边数,n 是顶点数。我以前用简单的数组做过很多次,但还没有用向量尝试过。 该类包括:
int n;
int m;
bool directed;
std::vector<std::list<std::pair<int, int>>> graph;
在graph.reserve(n)
之后,graph.size()
仍然是零。reserve
影响载体的容量,而不是其大小。然后graph[x - 1]
通过越界访问索引来表现出未定义的行为(任何值x
都会产生越界索引,因为向量为空(。
你可能的意思是graph.resize(n)
相关文章:
- 没有为自己的结构调用列表推回方法
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 如何将类成员方法的参数列表自动填充写入可变参数?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 有什么方法可以将元素添加到列表中,如图所示?
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 处理从列表中删除指向对象的指针的"healthy"方法是什么?
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 生成包含给定类型的 N 个参数的可变参数列表的最佳方法?
- C++中有没有一种方法可以通过指定列表中的每个成员变量来构造对象
- 在 c++ 中迭代对列表的正确方法?
- 获取位于特定区间的已排序值列表的子列表的最短方法
- 提供初始值设定项列表构造函数的有效方法
- C++ - 类方法函数指针unordered_map的初始化器列表
- gRPC trace.cc 的方法 TraceFlagList::Add(TraceFlag* flag) 使其链接列表
- 对列表类中的泛型方法禁用编译器警告 2100,该泛型方法可能包含指针,也可能不包含指针
- 方法的参数列表出错
- 参数列表中的模板方法"=0"
- 在初始化列表中初始化数组的更好方法
- g++4.8.2上列表方法参数默认初始化时出错