daydayup daydayup - 7 months ago 49
C++ Question

C++ priority_queue size() issue

I tried to get the size of an empty priority_queue. Something strange happened. Could anybody explain why this happened? Thanks a lot.

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

int main()
priority_queue<int, vector<int>, less<int> > asc_queue;
cout << asc_queue.size() << " " << asc_queue.size() - 1 << endl;


0 18446744073709551615


std::priority_queue::size() returns the size of the container as a std::size_t (technically the size_type of the underlying container of the priority queue) which is essentially an unsigned int - therefore trying to minus 1 from an empty container size gives you the unsigned decimal representation of 0xffffffffffffffffL which is why you get the large value you see.