为什么vector.size()-1提供垃圾值? [英] Why vector.size()-1 gives garbage value?

查看:140
本文介绍了为什么vector.size()-1提供垃圾值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试运行此代码

// vector::size
#include <iostream>
#include <vector>

int main ()
{
   std::vector<int> myints;
   std::cout << "size: " << myints.size() << '\n';
   std::cout << "size: " << myints.size()-1 << '\n';

 return 0; 
}

令人惊讶的是,输出结果已经出现

And Surprisingly the output came


0

0

垃圾价值

应该是


0

0

-1

这是:代码

推荐答案

myints.size() unsigned 类型:正式为 std :: vector< int> :: size_type 。从值为0的无符号类型中减去 1 在您的情况下会导致环绕效果

myints.size() is an unsigned type: formally a std::vector<int>::size_type. Subtracting 1 from an unsigned type with a value of 0 will cause wrap-around effects, in your case, to

std::numeric_limits<std::vector<int>::size_type>::max()

它会不会打印出垃圾值:但是上面的数字比2的大幂小1。

It would not have printed "garbage value": but the number above, which will be one less than a large power of 2.

这篇关于为什么vector.size()-1提供垃圾值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆