今天写代码时,有个点卡了我很久,最后一步步输出才发现问题出在.size()返回值上,记录一下。
先看代码
int cnt=-1; vectorv(5);//创建一个大小为5的vector if(cnt>=v.size()) cout<<"yes"; else cout<<"no";
之前我认为输出应该是“no”,但是其结果应该是“yes”!!!
这是因为.size()的返回值,是一个unsigned 类型,-1与其相比就会将-1看做4294967295 (unsigned(-1)=4294967295),导致-1>v.size()为真的结果。
这样出错真的很难被发现,所以以后还是不要直接调用.size()进行比较了,尽量赋值后再比较。
以下代码展示了list、map、set都有这样的特点
#includetypedef long long ll; using namespace std; const int maxn=1e5+5; int main(){ ios::sync_with_stdio(0); int cnt=-1; vector v(5); if(cnt>=v.size()) cout<<"yes"; else cout<<"no"; cout< l(5); if(cnt>=l.size()) cout<<"yes"; else cout<<"no"; cout< mp; mp[1]=1; if(cnt>=mp.size()) cout<<"yes"; else cout<<"no"; cout< s; s.insert(1); if(cnt>=s.size()) cout<<"yes"; else cout<<"no"; cout< =size) cout<<"yes"; else cout<<"no"; return 0; }
输出结果:
yes
yes
yes
yes
no



