C++ string::size_type

  从逻辑上讲,size()成员函数应该似乎返回整型数值,但事实上,size操作返回是string::size_type类型的值。string类类型和其他许多库类型都定义了一些配套类型(companion type)。通过这些配套类型,库函数的使用就与机器无关(machine-independent)。size_type就是这些配套类型中的一种。它定义为与unsigned型(unsigned int获unsigned long)具有相同含义,而且保证足够大的能够存储任意的string对象的长度。string::size_type它在不同的机器上,长度是可以不同的,并非固定的长度。但只要你使用了这个类型,就使得你的程序适合这个机器。与实际机器匹配。string对象的索引也应为size_type类型。

  npos表示size_type的最大值,用来表示不存在的位置。find()成员函数的返回值为size_type,平台编译器为32位,机器为64位。

	string s1 = "Hello";
	string::size_type count = 5;
	int c = 0;
	long k = 0;
	count=s1.find("w");
	c = s1.find("w");
	bool flag1 = (count == string::npos);
	bool flag2 = (c == string::npos);
	cout<<"flag1:"<<flag1<<endl<<"flag2:"<<flag2<<endl;
	cout<<"size_type:"<<count<<endl<<"int:"<<c<<endl;
	cout<<"string::pos值:"<<string::npos<<endl;
	cout<<"size of int:"<<sizeof(c)<<endl;
	cout<<"size of size_type:"<<sizeof(count)<<endl;
	cout<<"size of long:"<<sizeof(k)<<endl; 

运行结果: 

转载于:https://www.cnblogs.com/catpainter/p/8444751.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值