Files
reachability-algorithms/graph/graph.h

73 lines
1.3 KiB
C++

#ifndef GRAPH_H_
#define GRAPH_H_
#include <map>
#include <set>
#include <iostream>
namespace graph {
template<typename T>
class Graph {
public:
~Graph();
// Add edge between v and u
virtual void insert(const T& v, const T& u);
// Number of vertices
virtual std::uint16_t V();
// Number of edges
virtual std::uint16_t E();
// Output graph
virtual void output();
// Adjacency matrix representation
std::set<T> vertices;
std::map<T, std::set<T>> adjMatrix;
};
template<typename T>
Graph<T>::~Graph() {
vertices.clear();
adjMatrix.clear();
}
template<typename T>
inline void Graph<T>::insert(const T& v, const T& u) {
Graph<T>::vertices.insert(v);
Graph<T>::vertices.insert(u);
Graph<T>::adjMatrix[v].insert(u);
}
template<typename T>
std::uint16_t Graph<T>::V() {
return static_cast<std::uint16_t>(vertices.size());
}
template<typename T>
std::uint16_t Graph<T>::E() {
std::uint16_t edges = 0;
for (const auto& v : vertices) {
edges += static_cast<std::uint16_t>(adjMatrix[v].size());
}
return static_cast<std::uint16_t>(edges);
}
template<typename T>
void Graph<T>::output() {
for (const auto& v : vertices) {
for (const auto& u : adjMatrix[v]) {
std::cout << v << "->" << u << '|';
}
std::cout << '\n';
}
std::cout << '\n';
}
} // namespace graph
#endif