How to print graph using vector of vector ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>
using namespace std;
void addEdge( vector<vector<int> > adj, int, int);
void print_graph(vector<vector<int> > adj);


int main()
{
    
    vector<vector<int> > adj;
    addEdge(adj,1,2);
    addEdge(adj,1,3);
    addEdge(adj,1,4);
    addEdge(adj,2,3);
    addEdge(adj,3,4);
    print_graph(adj);
    return 0;
}

void addEdge(vector<vector<int> > adj, int u , int v)
{
    adj[u].push_back(v);
    
}

void print_graph( vector<vector<int> > adj)
{
    for( int i = 0; i < adj.size() ; i++ )
    {
        for( int j = 0 ; j < adj[i].size(); j++ )
        {
            cout<< adj[i][j];
        }
    }
}


Error : Segmentation fault ( core dump)

I just want to read and print the graph.
I have been told that use vector<vector<int> > or list<list<int> > .
I tried but getting above error.
Can anyone help me ??
if possible plz provide help with list<list<int> > also.
Thank you.
Last edited on
Meaningful variable names can act almost like a debugging tool and if addEdge() returns void it's result can't be used:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>

using vecvecInt = std::vector<std::vector<int>>;

vecvecInt& addEdge(vecvecInt& myVec, const size_t dim, const int val)
{
    std::vector<int> v(dim, val);
    myVec.push_back(v);
    return myVec;
}
void print_graph(const vecvecInt& myVec)
{
    for (const auto& elemOuter : myVec)
    {
        for (const auto& elemInner : elemOuter)
        {
            std:: cout << elemInner << " ";
        }
        std::cout << "\n";
    }
}

int main()
{
    std::vector<std::vector<int>> myVec{};
    myVec = addEdge(myVec, 1, 2);
    myVec = addEdge(myVec, 4, 1);
    myVec = addEdge(myVec, 3, 3);
    print_graph(myVec);
}

Topic archived. No new replies allowed.