Creating Your First Graph
- In your
main.cppimport Graaf:
#include <graaflib/graph.h>
- Define a directed graph
g
graaf::directed_graph<const char, int> g;
- Add vertices to the graph:
const auto a = g.add_vertex('a');
const auto b = g.add_vertex('b');
const auto c = g.add_vertex('c');
- Connect the vertices with edges:
g.add_edge(a, b, 1);
g.add_edge(a, c, 1);
- Putting it all together:
#include <graaflib/graph.h>
int main()
{
graaf::directed_graph<const char, int> g;
const auto a = g.add_vertex('a');
const auto b = g.add_vertex('b');
const auto c = g.add_vertex('c');
g.add_edge(a, b, 1);
g.add_edge(a, c, 1);
return 0;
}
Congratulations! You just created the following graph 🎉
Vertex ID lifecycle
A vertex’s ID is only valid for as long as that vertex exists. Once a vertex
is removed via remove_vertex(), its ID may be handed out again to a
different vertex added afterwards. Don’t hold on to a vertex_id_t past the
removal of the vertex it identifies.
Importing data with existing IDs
add_vertex() always has the graph assign the new vertex’s ID. If you’re
importing data that already has its own IDs (e.g. row numbers from a
database, or IDs from a file format), keep a map from those external IDs to
the graph-assigned vertex_id_ts and use it to translate IDs when adding
edges:
std::unordered_map<int, graaf::vertex_id_t> external_id_to_vertex_id;
for (const auto& record : records) {
const auto vertex_id = g.add_vertex(record.data);
external_id_to_vertex_id[record.external_id] = vertex_id;
}
for (const auto& [from_external_id, to_external_id] : record_links) {
g.add_edge(external_id_to_vertex_id.at(from_external_id),
external_id_to_vertex_id.at(to_external_id), 1);
}