size_type、size_t、different_type以及ptrdiff_t
2015-10-20 22:37
369 查看
size_type
在标准库string类型中,最容易令人产生误解就是size()成员函数的返回值了,如果不深入分析的话,大多人都会认为size()的返回值为int类型,其实不然。事实上,size操作返回的是string::size_type类型的值。 那怎样理解size_type这一类型呢,我引用《C++ Primer》一段原文简单解释一下:
string类类型和许多其他库类型都定义了一些配套类型(companion type)。通过这些配套类型,库类型的使用就能和机器无关(machine-independent)。size_type就是这些配套类型中的一种。它定义为与unsigned型(unsigned int 或 unsigned long)具有相同的含义,而且可以保证足够大能够存储任意string对象的长度。为了使用由string类型定义的size_type类型,程序员必须加上作用域操作符来说明所使用的size_type类型是由string类定义的。
/******************************************* * this is a simple demo to test size_type * * Auther : Jerry.Jiang * Date : 2011/08/20 * http://blog.csdn.net/jerryjbiao * *********************************************/ #include <iostream> #include <string> using namespace std; int main() { string str("This is a simple demo !"); for (string::size_type index = 0; index != str.size(); ++index) { cout << str[index]; } cout << endl; return 0; }
不仅string类型定义了size_type,其他标准库类型如vector::size_type,list::size_type,deque::size_type,map::size_type,multimap::size_type ,basic_string::size_type 等
size_t
size_t类型定义在cstddef头文件中,该文件是C标准库中的头文件 stddef.h 的C++版本。它是一个与机器相关的unsigned类型,其大小足以存储内存中对象的大小。与前面Demo中vector和string中的size操作类似,在标准库类型bitset中的size操作和count操作的返回值类型为size_t 。
/*********************************************** * this is a simple demo to test bitset::size_t * * Auther : Jerry.Jiang * Date : 2011/08/20 * http://blog.csdn.net/jerryjbiao * *********************************************/ #include <iostream> #include <bitset> using namespace std; int main() { //bitvec有32位,每位都是0 bitset<32> bitvec; cout << " bitvec : " << bitvec << endl; //count()统计bitvec中置1的个数 size_t bitcount = bitvec.count(); cout << "bitvec.count() :" << bitcount << endl; //size()统计bitvec二进制位的个数 size_t bitsize = bitvec.size(); cout << "bitvec.size() :" << bitsize << endl; return 0; }
different_type
一种由vector类型定义的signed整型,用于存储任意两个迭代器间的距离。ptrdiff_t
与size_t一样,定义在cstddef头文件中定义的与机器相关的有符号整型,该类型具有足够的大小存储两个指针的差值,这两个指针指向同一个可能的最大数组。相关文章推荐
- Linux C函数参考手册(PDF版)
- Lua教程(十七):C API简介
- C#实现打造气泡屏幕保护效果
- C/C++数据对齐详细解析
- 利用C语言来求最大连续子序列乘积的方法
- 字符串的组合算法问题的C语言实现攻略
- C 语言基础教程(我的C之旅开始了)[三]
- C++中的extern “C”用法详解
- C 语言基础教程(我的C之旅开始了)[七]
- 最大子矩阵问题实例解析
- C字符串操作函数实现方法小结
- 字典树的基本知识及使用C语言的相关实现
- 详解C语言中free()函数与getpagesize()函数的使用
- C/C++ 宏详细解析
- 使用C语言解决字符串全排列问题
- C/C++实现对STORM运行信息查看及控制的方法
- 用C#生成不重复的随机数的代码
- String.Format大全(C# Java)
- 在c和c++中实现函数回调