C++ string::size_type 類型
Posted on 2009-10-22 09:10 lantionzy 閱讀(12121) 評論(8) 編輯 收藏 引用 所屬分類: C++ Primerint main()
{
string str("Hello World!\n");
cout << "The size of " << str << "is " << str.size()
<< " characters, including the newline" << endl;
return 0;
}
從邏輯上來講,size() 成員函數(shù)似乎應(yīng)該返回整形數(shù)值,或是無符號整數(shù)。但事實(shí)上,size 操作返回的是 string::size_type 類型的值。{
string str("Hello World!\n");
cout << "The size of " << str << "is " << str.size()
<< " characters, including the newline" << endl;
return 0;
}
string 類類型和許多其他庫類型都定義了一些配套類型(companion type)。通過這些配套類型,庫類型的使用就能與機(jī)器無關(guān)(machine-independent)。size_type 就是這些配套類型中的一種。它定義為與 unsigned 型(unsigned int 或 unsigned long)具有相同的含義,而且可以保證足夠大能夠存儲任意 string 對象的長度。為了使用由 string 類型定義的 size_type 類型是由 string 類定義。任何存儲string的size操作結(jié)果的變量必須為string::size_type 類型。特別重要的是,不要把size的返回值賦給一個(gè) int 變量。
雖然我們不知道 string::size_type 的確切類型,但可以知道它是 unsigned 型。對于任意一種給定的數(shù)據(jù)類型,它的 unsigned 型所能表示的最大正數(shù)值比對應(yīng)的 signed 型要大一倍。這個(gè)事實(shí)表明 size_type 存儲的 string 長度是 int 所能存儲的兩倍。
使用 int 變量的另一個(gè)問題是,有些機(jī)器上 int 變量的表示范圍太小,甚至無法存儲實(shí)際并不長的 string 對象。如在有 16 位 int 型的機(jī)器上,int 類型變量最大只能表示 32767 個(gè)字符的 string 對象。而能容納一個(gè)文件內(nèi)容的 string 對象輕易就會超過這個(gè)數(shù)字。因此,為了避免溢出,保存一個(gè) stirng 對象 size 的最安全的方法就是使用標(biāo)準(zhǔn)庫類型 string::size_type。
string str("some string");
for (string::size_type index = 0; index != str.size(); ++index)
cout << str[index] << endl;
for (string::size_type index = 0; index != str.size(); ++index)
cout << str[index] << endl;
轉(zhuǎn)到博客首頁查看更多隨筆