v.size() return size_t not int 返回无符号整型数

简介:

In the C++ STL, the vector size() function return size_t, which is unsigned int, not int. So imagine this, define an empty vector<int> v, and v.size() should be 0, and you have a for loop, and has an end condition is v.size() - 1, which is 4294967295 actually, not -1. This might cause problem when i = 0, which can enter the for loop, but actually was supposed not entering it.

vector<int> v;
cout << v.size() << endl;      // 0
cout << v.size() - 1 << endl;  // 4294967295 
cout << v.size() - 2 << endl;  // 4294967294
cout << v.size() << endl;           // 0
cout << int(v.size() - 1) << endl;  // -1 
cout << int(v.size() - 2) << endl;  // -2

本文转自博客园Grandyang的博客,原文链接:返回无符号整型数v.size() return size_t not int ,如需转载请自行联系原博主。

相关文章
|
5月前
|
Python
在Python中,整型(int)
【4月更文挑战第9天】Python的整型(int)数据类型支持无限大小的整数,包括正数、负数和零。可通过加、减、乘、除、取模和幂运算进行操作。使用`int()`函数可进行类型转换,例如将浮点数转为整数。Python还支持位运算,如按位与、或、异或、取反、左移和右移。整型无固定范围,但大规模数据可能消耗大量内存。注意整数除法会丢失小数部分,浮点数转整数会截断。
46 1
|
5月前
|
存储 编译器 C++
C++系列-第1章顺序结构-4-整型int
C++系列-第1章顺序结构-4-整型int
|
5月前
牛客网刷题总结1.利用%符号获取特定位数的数字。2.强制类型转换 (将float转换为int )3.计算有关浮点型数据时,要注意你计算过程中所有的数据都是浮点型
牛客网刷题总结1.利用%符号获取特定位数的数字。2.强制类型转换 (将float转换为int )3.计算有关浮点型数据时,要注意你计算过程中所有的数据都是浮点型
58 0
|
12月前
|
存储 小程序 程序员
8k字详解整型(int)/字符型(char)/浮点型(float)/有符号(signed)/无符号(unsigned)数据在内存中的存储【程序员内功修炼/C语言】
8k字详解整型(int)/字符型(char)/浮点型(float)/有符号(signed)/无符号(unsigned)数据在内存中的存储【程序员内功修炼/C语言】
116 0
|
存储 自然语言处理 Java
[oeasy]python0072_整数类型_int_integer_整型变量
[oeasy]python0072_整数类型_int_integer_整型变量
76 0
|
存储 Java
【剑指offer知识点】Java中无符号整型、如何与int/long类型互相转化
【剑指offer知识点】Java中无符号整型、如何与int/long类型互相转化
407 0
【剑指offer知识点】Java中无符号整型、如何与int/long类型互相转化
|
Go
Golang 字符串([]string)数组转整型([]int)数组
Golang 字符串([]string)数组转整型([]int)数组
416 0
java中整型数据(byte、short、int、long)溢出的现象及原理
java中整型数据(byte、short、int、long)溢出的现象及原理