问题描述:使用优先队列(priority_queue)来实现大根堆和小根堆。在维护两个堆平衡的过程中,需要使用 priority_queue.size() 来判断两个堆的大小。因为 .size() 返回的是无符号类型,直接进行减法运算会导致错误。
错误代码
if(max_heap.size() - min_heap.size() > 1) Balance(1);
else if(min_heap.size() - max_heap.size() > 1) Balance(0);
对无符号类型进行减法运算时,如果结果为负数,C++ 会将其转换为一个非常大的无符号整数。这可能会导致条件判断失误,进而导致代码逻辑错误。
正确代码
(1)推荐:避免直接对无符号类型进行减法运算
if(max_heap.size() > min_heap.size() + 1) Balance(1);
else if(min_heap.size() > max_heap.size() + 1) Balance(0);
(2)不推荐:实在想用减法就用一个整型捕捉减法的结果
int cmp = max_heap.size() - min_heap.size();
if(cmp > 1) Balance(1);
else if(cmp < -1) Balance(0);
理解示例代码
#include<iostream>
#include<queue>
#include<typeinfo>
using namespace std;
priority_queue<int> heap;
int main(){
unsigned a=0, b=4;
if(a - b > 1){
cout << "a - b = " << a-b << endl;
cout << "type of a: " << typeid(a).name() << endl;
cout << "type of b: " << typeid(b).name() << endl;
cout << "type of priority_queue.size(): " << typeid(heap.size()).name() << endl;
}
return 0;
}
示例代码输出
a - b = 4294967292
type of a: j
type of b: j
type of priority_queue.size(): y
typeid().name() | 实际类型 |
b | bool |
c | char |
a | signed char |
h | unsigned char |
s | (signed) short (int) |
t | (unsigned) short (int) |
i | (signed) int |
j | (unsigned) int |
l | (signed) long (int) |
m | (unsigned) long (int) |
x | (signed) long long (int) |
y | (unsigned) long long (int) |
f | float |
d | double |
e | long double |
经验总结
(1)判断条件:尽量不要用减法,避免无符号整型减法造成的错误。
(2)priority_queue.size() 返回的类型是无符号类型,不适合直接作差。
标签:priority,int,long,queue,heap,减法,Bug,size From: https://blog.csdn.net/Junseer/article/details/141105642