爲什麼-1不能和vector.size()比較

爲什麼-1不能和vector.size()比較

在使用vector.size()做比較的時候可能會出現如下情況:

vector<int> nums={4,8,10,240};
int len=-1;
if(len<nums.size())
   	len=nums.size();
cout<<len<<endl;

此時程序的輸出是

-1

而不是預想中的

4

這是爲什麼呢?
查證了一下size()的返回值:

std::vector::size
size_type size() const noexcept;

發現該返回值類型是 size_type ,也就是容器中 typedef 之後的 size_t,而 size_t 的類型是:

std::size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.

也就是說size()返回的是一個無符號整數,而補碼存儲的-1用unsigned int 解讀則是4294967295,也就是unsigned int 的最大值,所以代碼中的 if 判斷永遠爲假。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章