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位。code

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; 

运行结果: 对象

相关文章
相关标签/搜索