Reputation: 43
Currently I am learning graph
implementation. I found 2 implementation namely matrix
and adjacency list
using vector
in cpp. But the problems I face are following
// Code taken from geeksforgeeks
vector<int> adj[V];
// adding edge from u to v
adj[u].push_back(v);
So I want a solution in cpp
which can solve above 2 problems.
Upvotes: 3
Views: 203
Reputation: 14863
This is by no mean efficient implementation, but a perhaps a set of pairs is what you are looking for.
#include <iostream>
#include <utility>
#include <set>
#include <algorithm>
template<class T>
class graph
{
public:
std::set<std::pair<T, T>> storage;
/* true item added, false otherwise */
bool add_edge(T v1, T v2)
{
auto ret = storage.insert(std::make_pair(v1, v2));
return ret.second;
}
/* return value: edges deleted */
int delete_edge(T v1, T v2)
{
return storage.erase(std::make_pair(v1, v2));
}
void print_graph()
{
std::for_each(storage.begin(), storage.end(),
[](std::pair<T, T> const& p) {
std::cout << p.first << "--> " << p.second << std::endl;
});
}
};
#include <iostream>
#include "graph.h"
int main()
{
graph<int> g;
g.add_edge(5, 4);
g.add_edge(5, 4);
g.add_edge(6, 2);
g.print_graph();
g.delete_edge(5, 4);
g.print_graph();
return 0;
}
Compile command
g++ -std=c++17 -Wall -Wextra -pedantic main.cpp
Output
5 --> 4
6 --> 2
/* Deleted 5 --> 4 */
6 --> 2
Upvotes: 0
Reputation: 1375
I have efficient and easiest implementation of graph
in cpp
. It solves all problems you mentioned above. It is called as vector in vector
.
// Suppose at start we have
// number of nodes
int nodes = 5;
// number of edges
int edges = 4;
// define graph
vector<vector<int>> graph(nodes, vector<int>());
int u, v; // edge from u -> v
for(int i=0;i<edges;i++){
cin >> u >> v;
graph[u].push_back(v);
}
// suppose we want to add node
graph.push_back(vector<int>());
// print graph content
int index = 0;
for(auto x : graph){
cout << index << "-> ";
for(auto y: x){
cout << y << " ";
}
cout << endl;
index ++;
}
5 4
0 1
0 2
2 1
2 3
0-> 1 2
1->
2-> 1 3
3->
4->
5-> // new node
Upvotes: 1