有关于C++中string的erase函数的问题

2025-04-08 09:30:41
推荐回答(3个)
回答1:

erase函数的原型如下:
(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 
#include 
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;
}

假如是删除数组中的一项,并不能说明erase的用法。

回答2:

npos就是表示无限大。



basic_string& erase(size_type p0=0,size_type n=npos);

表示从p0的位置,删除n个长度的字符。

  • 缺省p0等于0,表示从字符串头开始。

  • n缺省等于npos,表示删除p0以后的所有字符。 

回答3:

npos is a static member constant value with the greatest possible value for an element of type size_t.

This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".

As a return value, it is usually used to indicate no matches.

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.