C ++指针,迭代器,图的邻接表表示的问题

时间:2013-07-23 14:57:01

标签: c++ pointers iterator

我有一篇上一篇文章:"Trouble with List or Pointers,..."并收到了一些关于指针的非常有用的信息。在更好地理解变化后,我仍然有一些非常奇怪的行为:

创建两个顶点,然后在它们之间创建无向边。每个顶点都有一个指向入射在其上的边的指针列表。使用此图表,边缘计数不应为0.但在计算边缘的过程中,我看到我的边缘列表有不同的位置,这可以解释我的计数问题。

以下是couts的简要介绍:

顶点1列表的地址:0x1851018 顶点2的列表地址:0x1851038

在Vertex 1,我们有...... 边列表的地址是...... 0x1851068

在Vertex 2,我们有...... 边列表的地址是...... 0x1851098

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

struct undirected_edge;
class vertex;

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

class vertex
{
    int vertexLabel;
    std::list<undirected_edge*> edgeList;
public:
    int getVertexNumber(){return vertexLabel;}
    std::list<undirected_edge*> * getPointerOfEdgeList(){
        std::cout << vertexLabel << " has edge List at: " << &edgeList << "\n";
    return &edgeList;}

    vertex(int n){vertexLabel=n;}
};


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

public:
    void addVertex(vertex * v){graph.push_back(*v);}
    void createEdge(vertex * v1, vertex * v2);
    undirected_edge * getRandomEdge();
    void removeEdge(undirected_edge * e);
    int getNumberOfNodes(){return graph.size();}
    int getNumberOfEdges();
};
void buildGraph(undirected_graph *);

void undirected_graph::createEdge(vertex * v1, vertex * v2)
{
    std::list<undirected_edge*> * e1 = v1->getPointerOfEdgeList();
    std::list<undirected_edge*> * e2 = v2->getPointerOfEdgeList();
    undirected_edge * e = new undirected_edge;
    e->start=v1;
    e->end=v2;
    e1->push_back(e);
    e2->push_back(e);
    std::cout<< "The address of vertex 1's list: " << e1 << "\n";
    std::cout<< "The address of vertex 2's list: " << e2 << "\n";
}

int undirected_graph::getNumberOfEdges()
{    
    int size = getNumberOfNodes();
    std::list<vertex>::iterator it = graph.begin();
    int counter = 0;
    for (int i = 0; i < size; i++)
    {
        std::cout<<"At Vertex " << it->getVertexNumber() << " we have...\n";
        std::cout<<"The address of the edge list is... " << it->getPointerOfEdgeList() << "\n";
        counter = counter + it->getPointerOfEdgeList()->size();
        std::cout<<it->getPointerOfEdgeList()->size()<<"\n";
        it++;
    }
    return counter;
}


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

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

    g->addVertex(v1);           
    g->addVertex(v2);
    g->createEdge(v1,v2);

    std::cout<<"The total number of edges: " << g->getNumberOfEdges();  
}

1 个答案:

答案 0 :(得分:1)

调用addVertex(vertex * v)时,将顶点参数的副本添加到包含graph.push_back(*v)的列表中。因此顶点对象具有不同的地址。

您可能希望存储std::list<vertex*>图表,然后使用graph.push_back(v)