Home > front end >  Difference in queue sizes giving arbitrarily large value C
Difference in queue sizes giving arbitrarily large value C

Time:10-07

#include <iostream>
#include <queue>

using namespace std;

int main()
{
    // cout<<"Hello World";

    priority_queue<int> spq;  // max heap
    priority_queue <int, vector<int>, greater<int>> lpq; // min heap
    
    
    spq.push(1);
    
    lpq.push(2);
    lpq.push(3);
    
    
    cout << spq.size() - lpq.size() << endl;
    
    
    return 0;
}

This code is giving me un-expectedly very large value of 18446744073709551615

I am not able to understand the issue here.

CodePudding user response:

You have unsigned integer wrap-around.

spq.size() is 1, lpq.size() is 2.

So when you do 1 - 2, since you're using unsigned numbers, you don't end up in the negatives, you instead wrap around to the largest unsigned number you have, 18446744073709551615.

  • Related