1

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;
}

Output:

0 18446744073709551615
3
  • What exactly is your question? Commented Nov 20, 2016 at 1:24
  • why asc_queue.size()-1 is not -1? Commented Nov 20, 2016 at 1:27
  • 3
    Because it is an unsigned value. There is no -1 for unsigned values. Commented Nov 20, 2016 at 1:28

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It gives you the unsigned decimal representation of 0xffffffffffffffffL. No overflow here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.