我有一个以前的帖子:“列表或指针的问题,......”并收到了一些关于指针的非常有用的信息。在更好地理解实施更改后,我仍然有一些非常奇怪的行为:
创建两个顶点,然后在它们之间创建一个无向边。每个顶点都有一个指向其上的边的指针列表。使用此图,边数不应该为 0。但是在计算边的过程中,我看到我的边列表得到了不同的位置,这可能解释了我的计数问题。
以下是 couts 的简短读数:
顶点1的列表地址:0x1851018 顶点2的列表地址:0x1851038
在顶点 1 我们有......边缘列表的地址是...... 0x1851068
在顶点 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();
}