有什么方法可以将元素添加到列表中,如图所示?

Is there any way I can add elements to list like shown?

本文关键字:列表 方法 什么 添加 元素      更新时间:2023-10-16

我正在尝试将元素添加到向量中的列表中。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)