您的位置:首页 > 编程语言 > C语言/C++

c++中size_t和size_type的区别

2015-03-20 16:57 288 查看
size_t:

/*
   Define the size_t type in the std namespace if in C++ or globally if in C.
   If we're in C++, make the _SIZE_T macro expand to std::size_t
*/

#if !defined(_SIZE_T) && !defined(_SIZE_T_DEFINED)
#  define _SIZE_T_DEFINED
   typedef unsigned int size_t;
#  if defined(__cplusplus)
#    define _SIZE_T std::size_t
#  else
#    define _SIZE_T size_t
#  endif
#  endif


size_type:

由string类类型和vector类类型定义的类型,用以保存任意string对象或vector对象的长度,标准库类型size_type定义为unsigned类型。

ps :为了使自己的程序有很好的移植性,c++程序员应该尽量使用size_t和size_type而不是int,unsigned。

1. size_t是全局定义的类型;size_type是STL类中定义的类型属性,用以保存任意string和vector类对象的长度。

2. string::size_type 制类型一般就是unsigned int, 但是不同机器环境长度可能不同 win32 和win64上长度差别;size_t一般也是unsigned int。

3. 使用的时候可以参考:

string::size_type a =123;

vector<int>::size_type b=234;

size_t b=456;

4. size_t 使用的时候头文件需要 <cstddef> ;size_type 使用的时候需要<string>或者<vector>。

5. sizeof(string::size_type)

sizeof(vector<bool>::size_type)

sizeof(vector<char>::size_type)

sizeof(size_t)

上述长度均相等,长度为win32:4 win64:8

6. 二者联系:在用下标访问元素时,vector使用vector::size_type作为下标类型,而数组下标的正确类型则是size_t。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: