【问题标题】:Unable to represent graph using adjacency list in C++无法在 C++ 中使用邻接表来表示图形
【发布时间】:2018-09-18 16:33:26
【问题描述】:

我正在尝试使用 C++ 中图形的邻接表表示来表示图形。所以我尝试转换我在这个 youtube 视频https://www.youtube.com/watch?v=mQEv1QxaIuM&t=7s 中找到的这个 C(语言)代码。但是当我尝试用 C++ 编写这段代码时,我得到了一个错误。 VSStudio 编译器显示“表达式必须具有指针类型”。 (请注意,此视频为印地语。)

这是我的 C++ 代码(由于错误,尚未完成。)

// Adjacency List Representation of Graph

#include <iostream>

struct listNode // defining linked list
{
    int vertexNumber;
    listNode *next;
};

struct graph // defining graph
{
    int vertex;
    int edge;
    listNode *adj;

};

graph *adjacencyListOfGraph()
{
    int x, y;
    listNode *temp;
    graph *G = new graph;

    std::cout << "Enter the number of vertex and edges.\n";
    std::cin >> G->vertex >> G->edge;

    G->adj = new listNode[G->vertex];

    for (int i = 0; i < G->vertex; ++i)
    {
        G->adj[i]->vertexNumber = i;// this is where I'm getting an error
    }
}

【问题讨论】:

  • 那么如何在不使用任何类、向量或 malloc 的情况下在 C++ 中转换这段代码,几乎类似于纯 C++ 风格的 C 代码 - 这违背了使用的目的C++。
  • @maxim 嗯,我不能不同意你的观点!
  • 欢迎来到 Stack Overflow!请使用tour 并阅读How to Ask。关于您的问题,请提取minimal reproducible example。一旦您将代码缩减为显示该错误的尽可能小的示例,该错误可能会变得非常明显。
  • @UlrichEckhardt 现在更直接了吗?如果是,请不要投反对票!
  • 您删除了(不相关的)C 代码,这很好。但是,为什么我必须输入任何内容?如果不需要输入,请将其替换为硬编码值。如果不需要循环,请执行相同操作。继续这样做,直到没有任何东西可以删除!

标签: c++ pointers data-structures graph


【解决方案1】:

查看this question 的答案。 adj[i] 等价于 *(adj+i)。您从 G-&gt;adj 获取偏移量,然后取消引用,因此 G-&gt;adj[i].vertexNumber 是正确的语法。

(注意正确的拼写也是adjacency)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多