在MSDN中對erase的聲明為basic_string& erase(size_type p0=0,size_type n=npos);為什么這里第二個參數(shù)的默認值是npos,而不是_Len,我看過一個string變量內(nèi)部的數(shù)據(jù)成員,npos是一個巨大的不知所云的數(shù),而_Len才是整個字符串所包含的字符數(shù),而erase函數(shù)如果不指明第二個參數(shù),將刪除從索引的指定開始位置到字符串末尾的所有字符,照這么來說,第二個參數(shù)的默認值應(yīng)該為字符串長度才對啊。
2 回答

弒天下
TA貢獻1818條經(jīng)驗 獲得超8個贊
npos就是表示無限大。
basic_string& erase(size_type p0=0,size_type n=npos);
表示從p0的位置,刪除n個長度的字符。
缺省p0等于0,表示從字符串頭開始。
n缺省等于npos,表示刪除p0以后的所有字符。

九州編程
TA貢獻1785條經(jīng)驗 獲得超4個贊
erase函數(shù)的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是說有三種用法:
(1)erase(pos,n); 刪除從pos開始的n個字符,比如erase(0,1)就是刪除第一個字符
(2)erase(position);刪除position處的一個字符(position是個string類型的迭代器)
(3)erase(first,last);刪除從first到last之間的字符(first和last都是迭代器)
下面給一個例子:
// string::erase #include <iostream> #include <string> using namespace std; int main () { string str ( "This is an example phrase." ); string::iterator it; // 第(1)種用法 str.erase (10,8); cout << str << endl; // "This is an phrase." // 第(2)種用法 it=str.begin()+9; str.erase (it); cout << str << endl; // "This is a phrase." // 第(3)種用法 str.erase (str.begin()+5, str.end()-7); cout << str << endl; // "This phrase." return 0; } |
假如是刪除數(shù)組中的一項,并不能說明erase的用法。
- 2 回答
- 0 關(guān)注
- 175 瀏覽
添加回答
舉報
0/150
提交
取消