In this tutorial, we will learn how to change edges order in the graph edges adjacency list (please visit Wikipedia: Adjacency and degree for more details ). Indeed, it can be useful to sort the edges considering a metric.
We will create a graph with 4 nodes and 4 edges. Their "id number" will start from 0 just like in the figure below :
Following is the sample of code that created such a graph:
int main() { //create an empty graph Graph *graph=tlp::newGraph(); //build the graph node n0=graph->addNode(); node n1=graph->addNode(); node n2=graph->addNode(); node n3=graph->addNode(); //add three edges edge e0=graph->addEdge(n1,n2); edge e1=graph->addEdge(n0,n1); edge e2=graph->addEdge(n2,n0); edge e3=graph->addEdge(n3,n0);
As you can see, node 0 has three edges : edge 1,edge 2 and edge 3. And if we display its edges adjacency list (see last section for function void displayAdjacency(node n, Graph *graph)
) we obtain the following output :
1 2 3
Swapping edges can be easily done with the function, void Graph::swapEdgeOrder ( const node, const edge,const edge)
that will, as said swap two edges in the adjacent list of a node. Following is an example of its use :
//swap e1 and e3 graph->swapEdgeOrder(n0, e1, e3);
As you can see, the adjacency list has changed :
3 2 1
An other way to change the edges order is to use a vector of type edge and the function : void Graph::setEdgeOrder (const node, const std::vector < edge > )
, following is an example that will replace e1 and e3 in their original order :
vector<edge> tmp(2); tmp[0]=e1; tmp[1]=e3; graph->setEdgeOrder(n0,tmp);
And the new order :
1 2 3
#include <iostream> #include <tulip/Graph.h> #include <tulip/MutableContainer.h> /** * Tutorial 006 * * Create a graph * Order the edges around the nodes */ using namespace std; using namespace tlp; void buildGraph(Graph *graph) { //add three nodes node n0=graph->addNode(); node n1=graph->addNode(); node n2=graph->addNode(); //add three edges graph->addEdge(n1,n2); graph->addEdge(n0,n1); graph->addEdge(n2,n0); } void displayAdjacency(node n, Graph *graph) { Iterator<edge>*ite=graph->getInOutEdges(n); while(ite->hasNext()) cout << ite->next().id << " "; delete ite; cout << endl; } int main() { //create an empty graph Graph *graph=tlp::newGraph(); //build the graph node n0=graph->addNode(); node n1=graph->addNode(); node n2=graph->addNode(); node n3=graph->addNode(); //add three edges edge e0=graph->addEdge(n1,n2); edge e1=graph->addEdge(n0,n1); edge e2=graph->addEdge(n2,n0); edge e3=graph->addEdge(n3,n0); tlp::saveGraph(graph, "adj1.tlp"); //display current order of edge around n1 displayAdjacency(n0,graph); //swap e1 and e3 graph->swapEdgeOrder(n0,e1,e3); //display the new order of edge around n1 displayAdjacency(n0,graph); vector<edge> tmp(2); tmp[0]=e1; tmp[1]=e3; graph->setEdgeOrder(n0,tmp); //display the new order of edge around n1 displayAdjacency(n0,graph); delete graph; return EXIT_SUCCESS; }