queue declaration causing std::bad_alloc

208 views Asked by At

I wrote this code and it throws:

terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc
Aborted (core dumped)

I get this error whenever I declare queue<int> q(or deque<int> q1) inside shortest_reach() function, and as soon as I comment that line, code works just fine. I don't give very large inputs(so that it doesn't require large memory), but I still get this error.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <deque>
#include <queue>

using namespace std;

class Graph {
    vector <vector <int> > adj;
    public:
        Graph(int n) {
            adj.reserve(n);            
        }

        void add_edge(int u, int v) {
            adj[u].push_back(v);
            adj[v].push_back(u);            
        }

        void shortest_reach(int start, int n, vector<int> &dist) {
            // queue<int> q;
            // deque<int> q1;                               

        }

};

int main() {
    int queries;
    cin >> queries;

    for (int t = 0; t < queries; t++) {

      int n, m;
        cin >> n;
        // Create a graph of size n where each edge weight is 6: 
        Graph graph(n);
        cin >> m;
        // read and set edges
        for (int i = 0; i < m; i++) {
            int u, v;
            cin >> u >> v;
            u--, v--;
            // add each edge to the graph
            graph.add_edge(u, v);
        }
      int startId;
        cin >> startId;
        startId--;
        // Find shortest reach from node s
        vector<int> distances(n); 
        graph.shortest_reach(startId, n, distances);

        for (int i = 0; i < distances.size(); i++) {
            if (i != startId) {
                if(distances[i]!=0)
                    cout << distances[i]*6 << " ";
                else
                    cout << -1 << " ";
            }
        }
        cout << endl;
    }

    return 0;
}

This is the input I provide:

2
4 2
1 2
1 3
1
3 1
2 3
2

First line tells the number of test cases, then each of the test case is described. First line of each test case contains number of vertices and edges in the graph, and edges are described in the following lines. Last line of each test case specifies the starting vertex for some task that I had to perform.

Note: I have tried running it on two different machines, and I get the same error.

0

There are 0 answers