C++ string erase() 函数有2种用法,删除单个元素、删除一个区间内的所有元素。时间复杂度均为O(N).
#include<string>#include<iostream>
using namespace std;intmain(){// 删除单个元素
string ss ="12345";
cout <<"ss: "<< ss <<" "<< endl;
ss.erase(ss.begin()+4);
cout <<"ss.erase(ss.begin()+24: "<< ss << endl;// 删除1个区间内所有元素
cout << endl;
ss ="678910";
cout <<"ss: "<< ss <<" "<< endl;
ss.erase(ss.begin()+2, ss.end()-1);
cout <<"ss.erase(ss.begin()+2, ss.end()-1): "<< ss << endl;// 从起始位置,删除x个字符
cout << endl;
ss ="678910";
cout <<"ss: "<< ss <<" "<< endl;
ss.erase(3,3);
cout <<"ss.erase(3,3): "<< ss;return0;}
打印结果
ss:12345
ss.erase(ss.begin()+24:1234
ss:678910
ss.erase(ss.begin()+2, ss.end()-1):670
ss:678910
ss.erase(3,3):678
Process returned 0(0x0) execution time :0.018 s
Press any key to continue.