Search code examples
c++vectorgraphgraph-algorithm

undirected graph incidence matrix implementation


Here I wrote a little program to represent graph using incidence matrix, with use of vector of vector to incorporate dynamic memory allocation.

#include <iostream>
#include <vector>
#include <utility>
void print_graph(const std::vector<std::vector<int> > &adj);
void addEdge(std::vector<std::vector<int> >& adj, int u, int v);

int main()
{
// Initialise array to hold adjacency matrix, vec<>s is already dynamic
    std::vector<std::vector<int> > adj(3);
    addEdge(adj,0,1);     // edge from node 0 to node 1
    addEdge(adj,0,2);
    addEdge(adj,1,2);
    print_graph(adj);
  //  return 0;
}

void print_graph(const std::vector<std::vector<int> >& adj)
{
    for(std::size_t i = 0; i < adj.size(); i++ )
    {
        for(std::size_t j = 0 ; j < adj[i].size(); j++ )
        {
            std::cout << adj[i][j]<< "  ";
        }
        std::cout << std::endl;
    }
}

void addEdge(std::vector<std::vector<int> >& adj, int u , int v)
{
    adj[u][v]=1;
    adj[v][u]=1;
}

Program crashed...everyone segmentation fault comes I am lost even debugger's on. I pasted that to compiler explorer, feel that the std::__throw_bad_cast()@plt indicates a bug but i duno how to fix it... Ideas anyone?


Solution

  • This statement:

    std::vector<std::vector<int> > adj(3);
    

    defines a vector of 3 empty vectors. Try that:

    std::vector<std::vector<int> > adj(3, std::vector<int>(3));