加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么(0> v.size() – 1)对空向量求值为false?

发布时间:2020-12-16 10:43:57 所属栏目:百科 来源:网络整理
导读:我正在使用vector做某事并发现以下条件被评估为false, 我无法理解. 代码如下: #include "stdio.h"#include vectorusing namespace std;int main(){ // an empty vector vectorint v; // print 0 printf ("size of the vector is %d n",v.size()); // the c
我正在使用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,它是一个无符号整数类型(很可能与std :: size_t相同,通常是unsigned long(long)的typedef),因此你的v.size() – 1回绕,因为它永远不会是负数.

如果启用警告,编译器会告诉您正在混合已签名和未签名.对于GCC,-Wall启用相关警告(即-Wsign-compare)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读