小议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();

Thestringclass provides six search functions, each named as a variant offind. The operations all return astring::size_typevalue that is the index of where the match occurred, or a special value namedstring::nposif there is no match. Thestringclass definesnposas 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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/17912

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午6:37
下一篇 2023年2月7日 下午6:37

相关推荐