samedi 3 octobre 2020

C++ list/queue top return value

I have a C++ code as following :

#include <iostream>
#include <queue>
#include <list>
using namespace std;

int main(){
    priority_queue<pair<int, int>> q;
    q.push({8, 8});
    q.push({19, 19});
    q.push({23, 23});

    while (q.size() > 0){
        auto& cur = q.top();
        q.pop();
        cout << cur.first << " " << cur.second << " "; // returns 19 19 8 8 8 8
    }
    cout << endl;

    list<pair<int, int>> newq;
    newq.push_back({19, 19});
    newq.push_back({8, 8});
    newq.push_back({23, 23});
    while (newq.size() > 0){
        auto& cur = newq.front();
        newq.pop_front();
        cout << cur.first << " " << cur.second << " "; // returns 19 19 8 8 23 23
    }
    cout << endl;
    return 0;
}

Iterating over the list using auto& vs auto produces the same output. But I'm trying to understand why if I use auto& while iterating over the priority queue, the output is wrong. If I change it to auto my output is correct:

    priority_queue<pair<int, int>> q;
    q.push({8, 8});
    q.push({19, 19});
    q.push({23, 23});

    while (q.size() > 0){
        auto cur = q.top();
        q.pop();
        cout << cur.first << " " << cur.second << " "; // returns 23 23 19 19 8 8
    }
    cout << endl;

Thanks for any clarifications!

Aucun commentaire:

Enregistrer un commentaire