Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Boost Graph Library: Sample Code using Compressed Sparse Row Format.
#include <iostream>
#include <string>
#include <vector>
#include <boost/graph/compressed_sparse_row_graph.hpp>
using namespace std;
//properties of the graph
struct edge_property
{
double weight;
};
struct vertex_property
{
int id;
};
struct graph_property
{
string graph_name;
};
//type definition
using graph = boost::compressed_sparse_row_graph<
boost::bidirectionalS,
vertex_property,
edge_property,
graph_property>;
using edge = pair<int, int>;
using vertex_iterator = boost::graph_traits<graph>::vertex_iterator;
using edge_iterator = boost::graph_traits<graph>::edge_iterator;
using vertex_descriptor = boost::graph_traits<graph>::vertex_descriptor;
int main()
{
/*
* construct the graph
* using compressed sparse row format
*/
enum { A, B, C, D, E, F, N };
const int num_vertices = N;
const string name = "ABCDEF";
edge edge_array[] = {
edge(A, B), edge(A, D), edge(A, F),
edge(B, C), edge(B, D),
edge(C, D), edge(C, A),
edge(D, A),
edge(E, B), edge(E, C), edge(E, D),
edge(F, E)
};
const int num_edges = sizeof(edge_array)/sizeof(edge_array[0]);
vector<edge> edge_vector(edge_array, edge_array+num_edges);
graph_property graph_prop;
graph_prop.graph_name = "CSR graph";
auto tag = boost::edges_are_unsorted_multi_pass;
graph g(tag, edge_vector.begin(), edge_vector.end(), num_vertices, graph_prop);
vertex_iterator itr, itr_end;
for (boost::tie(itr, itr_end) = vertices(g); itr!=itr_end; itr++) {
cout << name[*itr] << " --> ";
for (auto ad_itr = adjacent_vertices(*itr, g); ad_itr.first!=ad_itr.second; ad_itr.first++) {
cout << name[*ad_itr.first] << ", ";
}
cout << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment