Guide > Graphs and Related Data Types > Parameterized Graphs > Example

Example of How to Use Parameterized Graphs

The following program is a very simple example of how to use a GRAPH. It generates a star-like directed GRAPH<string,int> G. Every node of G has a name of type string and every edge of G has a length of type double. Then it creates five nodes with names of German cities and four edges with lengths. It then iterates over all edges of G, computes the source and target of each edge, and outputs them. For every edge and every end node it also outputs the corresponding information.

#include <LEDA/graph/GRAPH.h>
#include <LEDA/core/string.h>

using namespace leda;

int main()
{
  //define parameterized directed graph   
  GRAPH<string,double> G;

  //create new nodes of G with name
  node v0=G.new_node("saarbruecken");   
  node v1=G.new_node("kaiserslautern");
  node v2=G.new_node("koeln");          
  node v3=G.new_node("muenchen");
  node v4=G.new_node("berlin");

  //create new edges with length
  G.new_edge(v0,v1,80.3);  
  G.new_edge(v0,v2,342.4);
  G.new_edge(v0,v3,678.1);  
  G.new_edge(v0,v4,877.9);
  
  edge e;
  forall_edges(e,G) {         //iterate over all edges e of G
    node source=G.source(e);  //compute source of e
    node target=G.target(e);  //compute target of e

    G.print_edge(e);          //print edge
    std::cout << " has source ";  
    G.print_node(source);     //print source
    std::cout << " and target ";
    G.print_node(target);     //print target
    std::cout << std::endl;

    //print node and edge information
    std::cout << "The distance from " 
              << G[source] << " to " 
              << G[target] << " is " 
              << G[e] << " km.\n\n";
  }

  return 0;
}

See also:

Manual Entries:

Page Parameterized Graphs

Iteration




Algorithmic Solutions Software GmbH