Why vector.size()-1 gives garbage value? [duplicate]

谁都会走 提交于 2020-07-04 04:28:09

问题


I had tried running this code

// 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

garbage Value

It should be

0

-1

Here's the :code


回答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()

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



来源:https://stackoverflow.com/questions/48646518/why-vector-size-1-gives-garbage-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!