Eagle186f
Eagle186f

Reputation: 55

'std::bad_alloc' while inserting elements in deque

I did some debugging and found it's the q.push_back(nbr) inside the while loop that's causing the error , I can't understand why the requested space is not being allocated. please help. Thank you .

vector<int> bfs2(int V, vector<int> adj2[])
{
    int src = 0;
    bool visited[V];

    for (int i = 0; i < V; i++)
    {
        visited[i] = false;
    }

    deque<int> q;
    q.push_back(src);
    visited[src] = true;

    vector<int> res;

    while (q.empty() != true)
    {
        int top = q.front();
        q.pop_front();

        res.push_back(top);

        vector<int> nbrsveec = adj2[top];

        for (int nbr : nbrsveec)
        {
            if (visited[nbr] != true)
            {
                // cout<<nbr<<endl;
                q.push_back(nbr);
                 visited[nbr] = true;
            }
        }
    }
     return res;
}

Upvotes: 1

Views: 478

Answers (1)

moerker
moerker

Reputation: 97

bad_alloc means that you are running out of memory. What system are you using?

Maybe you should define const vector<int> & nbrsveec to avoid the copy (or just directly use it in your for-loop).

Upvotes: 2

Related Questions