vendredi 20 décembre 2019

Why does std::queue first elements become 0?

So I have an underordered_map which maps integer to a pointer of queue. When I push them on queue and print them in the same code block in which they were pushed, they get correctly printed out, however when I print them after the code block, first few become 0. I am trying to do something which needs to store references of queue (How to maintain std:: queue in std::unordered_map without loosing changes being done on queue?).

Here is a working example.

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>

using namespace std;

int main() {
    unordered_map<int, queue<int>*> nodes;
    int count = 1;
    if(count == 1) {
        queue<int> q;
        queue<int>* qp = &q;
        while(count <= 10) {
            qp->push(count);
            count++;
        }
        nodes[1] = qp;
        /*queue<int>* qpr = nodes[1];
        while(!qpr->empty()) {
            cout << qpr->front() << endl;
            qpr->pop();
        }*/
    }

    queue<int>* qpr = nodes[1];
    while(!qpr->empty()) {
        cout << qpr->front() << endl;
        qpr->pop();
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire