小议size_t和size_type

偶尔在代码中中看到string::size_type,以前只用过size_t,很奇怪二者之间的关系。

首先在c语言中,已经有size_t类型了,该类型是sizeof()操作符(注意sizeof()不是函数)的返回值类型,编译器在实现的时候通常size_t类型设置为unsigned int型。

而C++中,string类型和许多其他库类型都定义了一些配套类型(companion type)。通过这些配套类型,库类型的使用就能与机器无关,size_type就是这些配套类型中的一种。string.find()函数的返回值就是size_type类型,注意下面的程序:

1 string::size_type index = str.find("tag");
2 if (index == string::npos)
3     do_someting();

The string class provides six search functions, each named as a variant of find. The operations all return a string::size_type value that is the index of where the match occurred, or a special value named string::npos if there is no match. The string class defines npos as a value that is guaranteed to be greater than any valid index.

string::npos是一个与机器无关的常量,注意size_type不要和int类型混用,如果将index类型换成int,可能会导致不可预料的错误。(ps:string::npos 一般被设置成 -1)

以下代码可以具体查看本地机器中,size_t和size_type的具体实现。

 1 #include<iostream>
 2  #include<vector>
 3  #include<typeinfo>
 4  
 5  using namespace std;
 6  
 7  int main()
 8  {
 9      cout << "typeid(size_t).name() = " << typeid(size_t).name() << endl;
10      cout << "typeid(vector<int>::size_type).name() = "
11           << typeid(vector<int>::size_type).name() << endl;
12      return 0;
13  }

 运行程序,可以看出二者的类型实际上是一样的。

转载于:https://www.cnblogs.com/9sheng/archive/2010/11/26/2684254.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值