列表或指针有问题,图的邻接表示 [英] Trouble with List or Pointers, Adjacency Representaiton of Graph

查看:90
本文介绍了列表或指针有问题,图的邻接表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是图形的邻接表表示的开始.
在main立即调用的buildGraph中,创建了两个顶点,然后在它们之间创建了一条边.但是,然后要求顶点的边列表的大小应返回1,而不是0.我曾尝试在各个地方放置cout,但我只是无法弄清楚问题出在哪里,但我怀疑这是由于以某种方式误解了指针.谢谢您的帮助!

The following code is the the beginning of an adjacency list representation of a graph.
In the buildGraph, which is immediately called by main, two vertices are created, then an edge is created between them. But then asking for the size of the edgelist of a vertex should return 1, not 0. I have tried putting couts in various places, and I'm just not able to figure out what the problem is, but I suspect it's due to a misunderstanding of pointers in some way. Thank you for your help!

#include "MinCut.h"
#include <iostream>
#include <list>

void buildGraph(undirected_graph *);
class vertex;

struct edge
{
    vertex * start;
    vertex * end;
};

class vertex
{
    int vertexNumber;
    std::list<edge> edges;
public:
    int getVertexNumber(){return vertexNumber;}
    std::list<edge> getEdges(){return edges;}
    vertex(int n){vertexNumber=n;}
};


class undirected_graph
{
private:
    std::list<vertex>  graph;

public:
    void addVertex(vertex v){graph.push_back(v);}
    void createEdge(vertex * v1, vertex * v2);
};


void undirected_graph::createEdge(vertex * v1, vertex * v2)
{
    std::list<edge> e1 = v1->getEdges();
    std::list<edge> e2 = v2->getEdges();
    edge e;
    e.start=v1;
    e.end=v2;
    e1.push_back(e);
    e2.push_back(e);
}

int main()
{
    undirected_graph myGraph;
    buildGraph(&myGraph);
    return 0;
}

void buildGraph(undirected_graph * g)
{
    vertex v1(1);
    vertex v2(2);

    g->addVertex(v1);
    g->addVertex(v2);
    g->createEdge(&v1,&v2);
    std::list<edge> e = v1.getEdges();
    std::cout<< "? " << e.size();
}

推荐答案

createEdge()中,您有以下内容:

e.start=v1;
e.start=v2;

应该是

e.start=v1;
e.end=v2;


您的问题出在createEdge中,e1和e2只是副本,因此更改不会影响实际的顶点对象. 这是我的解决方案,似乎正在起作用:


Your problem is in createEdge, e1 and e2 are just copies, so changes don't affect the actual vertex objects. Here's my solution, seems to be working:

vertex添加一个函数,如下所示:

Add a function to vertex like so:

void addEdge(edge &e){edges.push_back(e);}

然后在createEdge()中:

edge e;
e.start=v1;
e.end=v2;
v1->addEdge(e);
v2->addEdge(e);

这篇关于列表或指针有问题,图的邻接表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆