您的位置:首页 > Web前端

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头文件中定义的与机器相关的有符号整型,该类型具有足够的大小存储两个指针的差值,这两个指针指向同一个可能的最大数组。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C size_t