我正在使用 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");
}
}
最佳答案
这就是混合有符号和无符号时发生的情况。 v.size()
返回一个 size_type
,它是一个 unsigned
整数类型(很可能与 std::size_t
,通常是 unsigned long (long)
) 的 typedef,因此您的 v.size()-1
环绕,因为它永远不会是负数.
如果您启用警告,编译器会告诉您您正在混合签名和未签名。对于 GCC,-Wall
启用相关警告(即 -Wsign-compare
)
关于c++ - 为什么 (0 > v.size()-1) 对于空 vector 求值为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813963/