c++ - 为什么 (0 > v.size()-1) 对于空 vector 求值为 false?

标签 c++ vector

我正在使用 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/

相关文章:

python - 使用 ctypes 从 C++ 函数返回字符串给出大的 int,而不是 char 指针

c++ - C++中的线程共享数据

matlab - 向量函数始终是常数

c++ - 是否有一些 STL 函数可以获取两个 C++ vector 的笛卡尔积?

c++ - vector 与双端队列运算符[]

c++ - 数字的最大 K 积

c++ - gcc 4.9.2 和 gcc 5.3 之间正则表达式支持的差异

c++ - 我的函数链不想工作,为什么?

c++ - 我的 for 循环怎么搞砸了?

vector - 如何过滤自定义结构的向量?