Bug | priority_queue.size()无符号整型进行减法运算引发的惨案

问题描述:使用优先队列(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
表1:typeid().name()输出符号与实际变量类型对照表
typeid().name()实际类型
bbool
cchar
asigned char
hunsigned 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)
ffloat
ddouble
elong double


经验总结

(1)判断条件:尽量不要用减法,避免无符号整型减法造成的错误。

(2)priority_queue.size() 返回的类型是无符号类型,不适合直接作差。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值