字符串 erase() 函数为类似的调用给出不同的结果

The string erase() function is giving different results for similar calls

本文关键字:调用 结果 erase 函数 字符串      更新时间:2023-10-16

我尝试使用带有 2 个参数的string::erase()函数作为起点和终点,但它为相同类型的调用提供了不同的结果。

这是代码:

#include<iostream>
using namespace std;
int main(){
string s = "azxxzy";
s.erase(2,2);
cout << s;
s.erase(1,1);
cout << endl << s;
}

它删除 2 个字符,即第一次调用xx,但第二次调用它只删除一个z

你能解释一下为什么会这样吗?

更正-

问题是错误的,因为我使用了重载版本,即

'string& erase (size_t pos = 0, size_t len = NPOS(;'

但期望输出

'迭代器擦除(迭代器在前,迭代器在后('

你正在使用 std::string::erase(( 和以下概要:

string& erase (size_t pos = 0, size_t len = npos);

它将擦除在长度len的位置pos指定的字符串部分。请注意,仓位索引pos以 0 开头。len = npos的默认参数指示直到末尾的所有字符。

在您的示例中,这意味着:

string s = "azxxzy";
s.erase(2,2);        /* azzy: deleting 2 characters from position 2 */
s.erase(1,1);        /* azy:  deleting 1 character from position 1  */

在我的教科书中写道,std::string::erase的 2 个参数是iterator firstiterator last.这就是为什么我认为它给出了一个奇怪的结果。

你的意思是重载版本:

iterator erase (iterator first, iterator last);

但是您没有提供iterator.您正在传递int将隐式转换为size_t的文本。在我上面发布的链接中,您可以看到重载版本 + 示例。

我希望输出是"ay">

要使用iterator获得该输出,请使用std::string::begin()std::string::end()执行以下操作:

string s = "azxxzy";
s.erase(s.begin() + 1, s.end() - 1); /* ay: deleting characters        */
/* between 1st and last character */