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; 

運行結果: 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM