【问题标题】:Is there any way I can add elements to list like shown?有什么办法可以将元素添加到列表中,如图所示?
【发布时间】:2020-01-18 21:48:31
【问题描述】:

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

【问题讨论】:

  • 不确定您要执行的操作...您要将项目添加到图表中的列表还是添加列表到图表?
  • 我没有得到图表的容器格式。为什么是std::list?为什么不直接使用std::map&lt;std::pair, Edge&gt;,其中Edge 是包含更多信息的类型(如果需要)。
  • 您肯定在第一种方法(构造函数)中有错字。什么是graph 单独在一条线上?另外,我不明白您要做什么以及为什么向我们展示这两种方法/功能。
  • 这是一个更好的解决方案吗?我知道我占用了更多内存,但是在地图中搜索的时间复杂度是多少?是 log n 吗?
  • @Vojin 我们仍然不知道您要做什么。您的图表容器看起来不像是一个简单的图表。请在您的问题中添加更多信息。是的std::map 是 O(log n)。 std::unordered_map 是 O(1)。

标签: c++ list vector graph


【解决方案1】:

graph.reserve(n) 之后,graph.size() 仍然为零。 reserve 影响向量的容量,而不是其大小。然后graph[x - 1] 通过访问越界索引表现出未定义的行为(x 的任何值都会产生越界索引,因为向量是空的)。

你的意思可能是graph.resize(n)

【讨论】:

    猜你喜欢
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 2022-11-12
    • 1970-01-01
    • 2012-05-20
    • 2015-08-13
    相关资源
    最近更新 更多