我正在使用vector做某事并发现以下条件被评估为false,这是我无法理解的.
代码如下:
#include "stdio.h"
#include <vector>
using namespace std;
int main()
{
// an empty vector
vector<int> v;
// print 0
printf ("size of the vector is %d \n", v.size());
// the condition is false, why?
if (0 > v.size()-1) {
printf ("it should occur \n");
}
}
Run Code Online (Sandbox Code Playgroud)
Luc*_*ore 11
这是混合有符号和无符号时会发生的情况.v.size()
返回size_type
这是一个unsigned
整数类型(很可能是一样的std::size_t
,这往往是一个typedef unsigned long (long)
),所以你的v.size()-1
回绕,因为它永远是负数.
如果启用警告,编译器会告诉您正在混合已签名和未签名.对于GCC,-Wall
启用相关警告(即-Wsign-compare
)