I am trying to represent a graph where
edge:
struct edge{
char a;
char b;
int weight;
}
I am trying to add my graph in this data structure:
vector<list<edge*>> graph;
In AddEdge function I get memory access violation while trying to add list in ith index of vector
void Graph::addEdge(char start, char end, int weight)
{
int i = node_number(start); //returns index (e.g 0 if start == 'A')
int j = node_number(end);
Edge *s= new Edge (start, end, weight);
Edge* e=new Edge (end, start, weight);
graph[i].push_back(s); //memory violation
graph[j].push_back(e);
}
Now someone help me to add edges in my graph. Thanks!
EDIT:
I did debugging and the values of i and j are 0 and 1 respectively at the push_back() part. The debugger returns abort: memory violation the trace back is:
public:
_NODISCARD _Ty& operator[](const size_type _Pos)
{ // subscript mutable sequence
#if _ITERATOR_DEBUG_LEVEL != 0
_STL_VERIFY(_Pos < size(), "vector subscript out of range");
#endif /* _ITERATOR_DEBUG_LEVEL != 0 */
return (this->_Myfirst()[_Pos]);
}
The problem is with the size of vector because below initialization assigns size=0
vector<list<edge*>> graph;
I have fixed the code by resizing the graph vector before pushing.
Another solution would be to give initial size by
vector<list<edge*>> graph(20);
Related
This is a working Prim's algorithm taking in three ints. My issue is that my edges are letters, and not numbers. I can't seem to debug it to make it work with char, instead of int, so I am turning to you guys. Any help would be appreciated!
using namespace std;
# define INF 0x3f3f3f3f
// iPair ==> Integer Pair
typedef pair<int, int> iPair;
// This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// In a weighted graph, we need to store vertex
// and weight pair for every edge
list< pair<int, int> > *adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int u, int v, int w);
// Print MST using Prim's algorithm
void primMST();
};
// Allocates memory for adjacency list
Graph::Graph(int V)
{
this->V = V;
adj = new list<iPair> [V];
}
void Graph::addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
// Prints shortest paths from src to all other vertices
void Graph::primMST()
{
// Create a priority queue to store vertices that
// are being preinMST. This is weird syntax in C++.
// Refer below link for details of this syntax
// http://geeksquiz.com/implement-min-heap-using-stl/
priority_queue< iPair, vector <iPair> , greater<iPair> > pq;
int src = 0; // Taking vertex 0 as source
// Create a vector for keys and initialize all
// keys as infinite (INF)
vector<int> key(V, INF);
// To store parent array which in turn store MST
vector<int> parent(V, -1);
// To keep track of vertices included in MST
vector<bool> inMST(V, false);
// Insert source itself in priority queue and initialize
// its key as 0.
pq.push(make_pair(0, src));
key[src] = 0;
/* Looping till priority queue becomes empty */
while (!pq.empty())
{
// The first vertex in pair is the minimum key
// vertex, extract it from priority queue.
// vertex label is stored in second of pair (it
// has to be done this way to keep the vertices
// sorted key (key must be first item
// in pair)
int u = pq.top().second;
pq.pop();
inMST[u] = true; // Include vertex in MST
// 'i' is used to get all adjacent vertices of a vertex
list< pair<int, int> >::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
{
// Get vertex label and weight of current adjacent
// of u.
int v = (*i).first;
int weight = (*i).second;
// If v is not in MST and weight of (u,v) is smaller
// than current key of v
if (inMST[v] == false && key[v] > weight)
{
// Updating key of v
key[v] = weight;
pq.push(make_pair(key[v], v));
parent[v] = u;
}
}
}
// Print edges of MST using parent array
for (int i = 1; i < V; ++i)
printf("%d - %d\n", parent[i], i);
}
I tried changing the typedef pair to <char, char>, and the *adj to <char, char>. The problem arrives in the function addEdge, using the list to create my graph.
Your code seems to be taken from here.
When you run the code online there everything works fine.
You can diff your version with the theirs see what went wrong.
This piece of code is getting quite on my nerves. Been debugging it for a while, cant believe how rusty i've got on c++.
I'm trying to model a graph to run some simple algorithms on, but that doesn't seem to work out so well. Every vertex contains a forward list to his neighbors, however when inserting the elements their obviously present.. Until I reach the print function; at that time the forward list is empty.
I've tried to allocate the forward_list using new aswell, as scoping could be an explication for it.. No luck there either..
#include <iostream>
#include <vector>
#include <set>
#include <forward_list>
#include <fstream>
using namespace std;
typedef struct Vertex Vertex;
struct Vertex {
unsigned id;
forward_list<Vertex*>_next;
bool operator < (const Vertex &other) const { return id < other.id; };
};
typedef set<Vertex> Graph;
typedef vector<Vertex*> Index;
typedef pair<unsigned, unsigned> Edge;
typedef forward_list<Vertex*> Neighbors;
// Function: process_line()
// Purpose: process a specific line from the file.
// Params: line to process
Edge process_line(string line){
unsigned vertex_from;
unsigned vertex_to;
int idx = line.find(" ");
vertex_from = (unsigned)stoul(line.substr(0, idx));
vertex_to = (unsigned)stoul(line.substr(idx+1, line.length()));
return make_pair(vertex_from, vertex_to);
}
// Function: load_graph()
// Purpose: load graph from file in relation
// Params: path, and reference to graph and index
bool load_graph(string file_path, Graph &graph, Index &index){
string line;
ifstream file(file_path);
bool foundEmptyLine = false;
if(file.is_open()){
while(getline(file, line)){
if(line.empty()){
foundEmptyLine = true;
continue;
}
if(!foundEmptyLine){
// processing vertexes
Vertex *vertex = new Vertex;
vertex->id = stoul(line);
graph.insert(*vertex);
index.emplace_back(vertex);
}else{
//Processing relations
Edge edge = process_line(line);
Vertex* neighbor = index.at(edge.second);
Vertex* source = index.at(edge.first);
// Lookup edge in index
source->_next.emplace_front(neighbor);
// ITEMS PRESENT! <----------------------
}
}
file.close();
}else{
cout << "Unable to open " << file_path;
return false;
}
return true;
}
void print_graph(Graph &graph){
for(Graph::iterator it = graph.begin(); it != graph.end(); ++it){
Neighbors neighs = it->_next;
cout << "Node: " << it->id << " neighbors: " neighs.empty();
cout << endl;
}
}
// Entry point.
int main() {
Graph graph;
Index index;
load_graph("graph_1.txt", graph, index);
print_graph(graph);
}
This is once again the same problem as yesterday.
Let's try to recapitulate the std::set
Since C++11 the iterator of a std::set is always an iterator to const value_type. This is because when we change an entry of a std::set this entry would need to be placed somewhere else in the data structure.
When we insert something into a std::set, two signatures are provided:
pair<iterator,bool> insert (const value_type& val);
pair<iterator,bool> insert (value_type&& val);
But in any case the insertion copies or moves the element into the container.
So in your case when you do
Vertex *vertex = new Vertex;
vertex->id = stoul(line);
graph.insert(*vertex);
index.emplace_back(vertex);
First you allocate memory (which by the way you never delete! You will leak much memory, which you can check using valgrind). Then you insert a copy of your vertex into the std::set and insert the pointer of your allocated memory into the std::vector.
When you then later do
Vertex* neighbor = index.at(edge.second);
Vertex* source = index.at(edge.first);
// Lookup edge in index
source->_next.emplace_front(neighbor);
You take the Vertex from your vector (remember, this is the vertex which you allocated with new). And insert another vertex (also dynamically allocated) into its std::forward_list. But: They have nothing to do with the vertex which are in your std::set.
So when you then later go through your std::set:
for (Graph::iterator it = graph.begin(); it != graph.end(); ++it)
This is completely unrelated to what you did when when inserting the edges - and all std::forward_lists are empty.
Side notes:
This is something you had to use in C, but not in C++!
typedef struct Vertex Vertex;
This one you should place above:
typedef forward_list<Vertex*> Neighbors;
It doesn't make sense to declare the type of Neighbors after you declared _next, because _next has this type.
Use const whereever you can, and cbegin / cend whereever you can (I already told you this yesterday), e.g.:
for(Graph::iterator it = graph.cbegin(); it != graph.cend(); ++it){
It doesn't make a difference here, but if you change the type of graph at some point, begin() may return a iterator to value_type instead of const value_type
Modified the graph to keep references to the existing vertices. I'm still not sure why this fixed it---but felt like giving a heads-up.
I am trying to write a function InsertVector that inserts an element (elem) into a vector in a position pos and then displaces all other values to the right, truncating the last value of the vector and returning its value; sz is the size of the vector.
Here is the code:
//InsertVector function:
int InsertVector (vector <int> V, int sz, int pos, int elem) {
int tmp=V.at(sz-1);
V.insert(V.begin()+pos-1, elem);
for(int i(pos);i<=sz-2;i=i+1) {
int tmp2(V.at(i));
V.at(i)=V.at(i-1);
V.at(i+1)=tmp2;
}
return tmp;
And here is my attempt to test the function on the main:
int main() {
vector<int>V;
V.push_back(2);
V.push_back(3);
V.push_back(4);
int sz(0);
sz=V.size();
int pos(0);
int elem(0);
cout<<"enter the position desired to modify here"<<endl;
cin>>pos;
cout<<"enter value to replace with here"<<endl;
cin>>elem;
InsertVector(V, sz, pos, elem);
PrintVector(V, sz);
}
note: PrintVector is another function I created that prints the elements of the vector and that has the following form:
void PrintVector(const vector <int> v1, int sz) {
for (int i(0);i<sz;i++) {
cout<<"V["<<i<<"] ="<<v1[i]<<endl;
}
}
When I compile Xcode gives an error (lldb).
Thank you in advance.
You don't need to displace all the values to right. V.insert() will do that itself. You can just remove the last element to truncate the list. To remove the last element, use v.pop_back()
the problem is documented in the code, look at him. I try to push_back an edge but it is not inserted. Maybe I should initialize even the lists but I've done in the constructor and nothing changes
Here is the function where I try to add the edge to teh adjacency list:
void Graph::addEdge(int vertex1, int vertex2){
if(!adjacent(vertex1, vertex2)) // if there isn't yet a Edge
adjacency_list[vertex1].push_back(Edge(vertex2, 1)); // add this edge without weight
std::cout << Edge(vertex2, 1) << std::endl; // THE OBJECT EDJE IS PROPERLY CREATED
std::cout << adjacency_list[vertex1].size() << std::endl; // THE SIZE IS EVERYTIME 0
printlist(adjacency_list[vertex1]); // THIS FUNCTION PRINTS JUST end, IN THE LIST THERE IS NOTHING
}
And here the constructor of graph, where there is the adjacency list variable and his initialization
class Graph{
public:
//Graph constructor that takes as parameter the number of vertices in the Graph
Graph(int NumberOfVertices):vertices(NumberOfVertices),
edges(0),
adjacency_list(NumberOfVertices){
for(int x = 0; x < numberOfVertices; x++) adjacency_list[x] = std::list<Edge>();
};
~Graph() { adjacency_list.clear(); }
int V() const { return vertices; }
int E() const { return edges; }
Edge returnEdge(std::list<Edge> list, const int vertex2);
bool adjacent (int vertex1, int vertex2);
std::list<Edge> neighbors(int vertex1) const;
void addEdge(int vertex1, int vertex2);
Edge *deleteFromList(Edge *list, const int vertex2);
void deleteEdge(int vertex1, int vertex2);
int getEdgeWeight(int vertex1, int vertex2);
void setEdgeWeight(int vertex1, int vertex2, int weight);
int incrementEdges() { edges++; } //increment by 1 the number of edges
private: int vertices, //number of vertices
edges; //number of edges
std::vector<std::list<Edge> > adjacency_list; //adjacency_list: every element of index x the vector is a list of edges from x
};
I'm wondering if I should initialize every lists in the adjacency_list vector but I don't know how to do that. How can I fix the problem?
There is a possible out-of-range problem in the line adjacency_list[vertex1].push_back(Edge(vertex2, 1)); Namely operator[] does not signal if the requested index is out of range. To resolve this issue you can
check the maximum index for adjacency_list vector by adjacency_list.max_size() method and then resize the vector, if necessary, using adjacency_list.resize() or
use adjacency_list.at() to index the vector but check for the out-of-range exception.
For the performance reason it would be the most convenient to build the large enough vector at the beginning.
Yet another way could be to use map<list<Edge> > (or unordered_map) instead of vector.
I was wondering about a quick to write implementation of a graph in c++. I need the data structure to be easy to manipulate and use graph algorithms(such as BFS,DFS, Kruskal, Dijkstra...).
I need this implementation for an algorithms Olympiad, so the easier to write the data structure the better.
Can you suggest such DS(main structs or classes and what will be in them). I know that an Adjacency list and Adjacency matrix are the main possibilities, but I mean a more detailed code sample.
For example I thought about this DS last time I had to implement a graph for DFS:
struct Edge {
int start;
int end;
struct Edge* nextEdge;
}
and then used a array of size n containing in its i'th place the Edge List(struct Edge) representing the edges starting in the i'th node.
but when trying to DFS on this graph I had to write a 50 line code with about 10 while loops.
What 'good' implementations are there?
Below is a implementation of Graph Data Structure in C++ as Adjacency List.
I have used STL vector for representation of vertices and STL pair for denoting edge and destination vertex.
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
struct vertex {
typedef pair<int, vertex*> ve;
vector<ve> adj; //cost of edge, destination vertex
string name;
vertex(string s) : name(s) {}
};
class graph
{
public:
typedef map<string, vertex *> vmap;
vmap work;
void addvertex(const string&);
void addedge(const string& from, const string& to, double cost);
};
void graph::addvertex(const string &name)
{
vmap::iterator itr = work.find(name);
if (itr == work.end())
{
vertex *v;
v = new vertex(name);
work[name] = v;
return;
}
cout << "\nVertex already exists!";
}
void graph::addedge(const string& from, const string& to, double cost)
{
vertex *f = (work.find(from)->second);
vertex *t = (work.find(to)->second);
pair<int, vertex *> edge = make_pair(cost, t);
f->adj.push_back(edge);
}
It really depends on what algorithms you need to implement, there is no silver bullet (and that's shouldn't be a surprise... the general rule about programming is that there's no general rule ;-) ).
I often end up representing directed multigraphs using node/edge structures with pointers... more specifically:
struct Node
{
... payload ...
Link *first_in, *last_in, *first_out, *last_out;
};
struct Link
{
... payload ...
Node *from, *to;
Link *prev_same_from, *next_same_from,
*prev_same_to, *next_same_to;
};
In other words each node has a doubly-linked list of incoming links and a doubly-linked list of outgoing links. Each link knows from and to nodes and is at the same time in two different doubly-linked lists: the list of all links coming out from the same from node and the list of all links arriving at the same to node.
The pointers prev_same_from and next_same_from are used when following the chain of all the links coming out from the same node; the pointers prev_same_to and next_same_to are instead used when managing the chain of all the links pointing to the same node.
It's a lot of pointer twiddling (so unless you love pointers just forget about this) but query and update operations are efficient; for example adding a node or a link is O(1), removing a link is O(1) and removing a node x is O(deg(x)).
Of course depending on the problem, payload size, graph size, graph density this approach can be way overkilling or too much demanding for memory (in addition to payload you've 4 pointers per node and 6 pointers per link).
A similar structure full implementation can be found here.
This question is ancient but for some reason I can't seem to get it out of my mind.
While all of the solutions do provide an implementation of graphs, they are also all very verbose. They are simply not elegant.
Instead of inventing your own graph class all you really need is a way to tell that one point is connected to another -- for that, std::map and std::unordered_map work perfectly fine. Simply, define a graph as a map between nodes and lists of edges. If you don't need extra data on the edge, a list of end nodes will do just fine.
Thus a succinct graph in C++, could be implemented like so:
using graph = std::map<int, std::vector<int>>;
Or, if you need additional data,
struct edge {
int nodes[2];
float cost; // add more if you need it
};
using graph = std::map<int, std::vector<edge>>;
Now your graph structure will plug nicely into the rest of the language and you don't have to remember any new clunky interface -- the old clunky interface will do just fine.
No benchmarks, but I have a feeling this will also outperform the other suggestions here.
NB: the ints are not indices -- they are identifiers.
The most common representations are probably these two:
Adjacency list
Adjacency matrix
Of these two the adjacency matrix is the simplest, as long as you don't mind having a (possibly huge) n * n array, where n is the number of vertices. Depending on the base type of the array, you can even store edge weights for use in e.g. shortest path discovery algorithms.
I prefer using an adjacency list of Indices ( not pointers )
typedef std::vector< Vertex > Vertices;
typedef std::set <int> Neighbours;
struct Vertex {
private:
int data;
public:
Neighbours neighbours;
Vertex( int d ): data(d) {}
Vertex( ): data(-1) {}
bool operator<( const Vertex& ref ) const {
return ( ref.data < data );
}
bool operator==( const Vertex& ref ) const {
return ( ref.data == data );
}
};
class Graph
{
private :
Vertices vertices;
}
void Graph::addEdgeIndices ( int index1, int index2 ) {
vertices[ index1 ].neighbours.insert( index2 );
}
Vertices::iterator Graph::findVertexIndex( int val, bool& res )
{
std::vector<Vertex>::iterator it;
Vertex v(val);
it = std::find( vertices.begin(), vertices.end(), v );
if (it != vertices.end()){
res = true;
return it;
} else {
res = false;
return vertices.end();
}
}
void Graph::addEdge ( int n1, int n2 ) {
bool foundNet1 = false, foundNet2 = false;
Vertices::iterator vit1 = findVertexIndex( n1, foundNet1 );
int node1Index = -1, node2Index = -1;
if ( !foundNet1 ) {
Vertex v1( n1 );
vertices.push_back( v1 );
node1Index = vertices.size() - 1;
} else {
node1Index = vit1 - vertices.begin();
}
Vertices::iterator vit2 = findVertexIndex( n2, foundNet2);
if ( !foundNet2 ) {
Vertex v2( n2 );
vertices.push_back( v2 );
node2Index = vertices.size() - 1;
} else {
node2Index = vit2 - vertices.begin();
}
assert( ( node1Index > -1 ) && ( node1Index < vertices.size()));
assert( ( node2Index > -1 ) && ( node2Index < vertices.size()));
addEdgeIndices( node1Index, node2Index );
}
There can be an even simpler representation assuming that one has to only test graph algorithms not use them(graph) else where. This can be as a map from vertices to their adjacency lists as shown below :-
#include<bits/stdc++.h>
using namespace std;
/* implement the graph as a map from the integer index as a key to the adjacency list
* of the graph implemented as a vector being the value of each individual key. The
* program will be given a matrix of numbers, the first element of each row will
* represent the head of the adjacency list and the rest of the elements will be the
* list of that element in the graph.
*/
typedef map<int, vector<int> > graphType;
int main(){
graphType graph;
int vertices = 0;
cout << "Please enter the number of vertices in the graph :- " << endl;
cin >> vertices;
if(vertices <= 0){
cout << "The number of vertices in the graph can't be less than or equal to 0." << endl;
exit(0);
}
cout << "Please enter the elements of the graph, as an adjacency list, one row after another. " << endl;
for(int i = 0; i <= vertices; i++){
vector<int> adjList; //the vector corresponding to the adjacency list of each vertex
int key = -1, listValue = -1;
string listString;
getline(cin, listString);
if(i != 0){
istringstream iss(listString);
iss >> key;
iss >> listValue;
if(listValue != -1){
adjList.push_back(listValue);
for(; iss >> listValue; ){
adjList.push_back(listValue);
}
graph.insert(graphType::value_type(key, adjList));
}
else
graph.insert(graphType::value_type(key, adjList));
}
}
//print the elements of the graph
cout << "The graph that you entered :- " << endl;
for(graphType::const_iterator iterator = graph.begin(); iterator != graph.end(); ++iterator){
cout << "Key : " << iterator->first << ", values : ";
vector<int>::const_iterator vectBegIter = iterator->second.begin();
vector<int>::const_iterator vectEndIter = iterator->second.end();
for(; vectBegIter != vectEndIter; ++vectBegIter){
cout << *(vectBegIter) << ", ";
}
cout << endl;
}
}
Here is a basic implementation of a graph.
Note: I use vertex which is chained to next vertex. And each vertex has a list pointing to adjacent nodes.
#include <iostream>
using namespace std;
// 1 ->2
// 1->4
// 2 ->3
// 4->3
// 4 -> 5
// Adjacency list
// 1->2->3-null
// 2->3->null
//4->5->null;
// Structure of a vertex
struct vertex {
int i;
struct node *list;
struct vertex *next;
};
typedef struct vertex * VPTR;
// Struct of adjacency list
struct node {
struct vertex * n;
struct node *next;
};
typedef struct node * NODEPTR;
class Graph {
public:
// list of nodes chained together
VPTR V;
Graph() {
V = NULL;
}
void addEdge(int, int);
VPTR addVertex(int);
VPTR existVertex(int i);
void listVertex();
};
// If vertex exist, it returns its pointer else returns NULL
VPTR Graph::existVertex(int i) {
VPTR temp = V;
while(temp != NULL) {
if(temp->i == i) {
return temp;
}
temp = temp->next;
}
return NULL;
}
// Add a new vertex to the end of the vertex list
VPTR Graph::addVertex(int i) {
VPTR temp = new(struct vertex);
temp->list = NULL;
temp->i = i;
temp->next = NULL;
VPTR *curr = &V;
while(*curr) {
curr = &(*curr)->next;
}
*curr = temp;
return temp;
}
// Add a node from vertex i to j.
// first check if i and j exists. If not first add the vertex
// and then add entry of j into adjacency list of i
void Graph::addEdge(int i, int j) {
VPTR v_i = existVertex(i);
VPTR v_j = existVertex(j);
if(v_i == NULL) {
v_i = addVertex(i);
}
if(v_j == NULL) {
v_j = addVertex(j);
}
NODEPTR *temp = &(v_i->list);
while(*temp) {
temp = &(*temp)->next;
}
*temp = new(struct node);
(*temp)->n = v_j;
(*temp)->next = NULL;
}
// List all the vertex.
void Graph::listVertex() {
VPTR temp = V;
while(temp) {
cout <<temp->i <<" ";
temp = temp->next;
}
cout <<"\n";
}
// Client program
int main() {
Graph G;
G.addEdge(1, 2);
G.listVertex();
}
With the above code, you can expand to do DFS/BFS etc.