I was writing the code for the problem. Median of the stream of integers when I encountered an issue. Note that this issue is not the algorithmic but rather ambiguous behavior of the priority_queue size.
#include <bits/stdc++.h> using namespace std; priority_queue<double> small; priority_queue<double, vector<double>, greater<double> > large; void rebalance() { cout << "Initial size\n"; cout << "small " << small.size() << " large " << large.size() << endl; if (small.size() - large.size()>1) { large.push(small.top()); small.pop(); } else if (large.size() - small.size()>1) { cout << "Unexpectedly goes here\n"; cout << "garbage size difference " << large.size() - small.size() << endl; small.push(large.top()); large.pop(); } } void addNum(int num) { if (small.size() == 0 || num<small.top()) { small.push(num); } else { large.push(num); } rebalance(); } double findMedian() { if (small.size() == large.size()) { double ans = (small.top() + large.top()) / 2.0; return ans; } else if (small.size()>large.size()) { return (double)small.top(); } else { return (double)large.top(); } } int main() { std::ios_base::sync_with_stdio(false); int num = 5; addNum(num); cout << findMedian() << endl; return 0; } The output for this code is
Initial size small 1 large 0 Unexpectedly goes here garbage size difference 18446744073709551615 fish: “./a.out” terminated by signal SIGSEGV (Address boundary error) In the rebalance function the initial size of small is 1 and large is 0 which suggest that the loop should neither enter the if condition nor the else if condition but the loop enters the else if condition with a garbage value in size.why does this happen? Moreover I tried saving the small and large size in an integer variable and then comparing them in conditionals,which lead to acceptance of the code. Hence the algorithm handles the correctness.
What leads to this garbage value?
#include <bits/stdc++.h>andusing namespace std;are bad practice. Together they magnify each other's worst ill effects. Be very cautious. If you start encountering insane mystery errors, one of the first things you should do is remove these two lines.stdnamespace and require scope resolution. And then along comesusing namespace stdto remove that protection. How much time are you willing to spend on figuring out why the compiler's telling you that your polynomial functionlaguerreis ambiguous? Show caution.