介绍一下删除函数erase,老方法,新建cpp文件,并找到string的erase成员函数,可以看到,erase有3个重载函数
右键转到定义,可以查看erase的源码
_Myt& erase(size_type _P0 = 0, size_type _M = npos){ if (_Len _Split(); if (_Len - _P0 if (0 < _M) { _Tr::move(_Ptr + _P0, _Ptr + _P0 + _M, _Len - _P0 - _M); size_type _N = _Len - _M; if (_Grow(_N)) _Eos(_N); } return (*this); }iterator erase(iterator _P){ size_t _M = _Pdif(_P, begin()); erase(_M, 1); return (_Psum(_Ptr, _M));}iterator erase(iterator _F, iterator _L){ size_t _M = _Pdif(_F, begin()); erase(_M, _Pdif(_L, _F)); return (_Psum(_Ptr, _M)); }
可以看到,erase重载函数之间又有相互调用,下面看例子
string str = "Hello_World_Welcome";cout << "str -> " << str << endl;cout << "str.begin() -> " << str.begin() << "\tstr.end()-1 -> " << str.end()-1 << endl << endl ;cout << "iterator erase(iterator first, iterator last)" << endl;string::iterator iter = str.begin();iter = str.erase(str.begin()+5, str.end()-9);cout << "after str.erase(str.begin()+5, str.end()-9) -> " << str << endl << "return iter -> " << *iter << endl;str = "Hello_World_Welcome";iter = str.erase(str.begin()+3, str.end()-8);cout << "after str.erase(str.begin()+3, str.end()-8) -> " << str << endl << "return iter -> " << *iter << endl;cout << "############################" << endl << endl;cout << "string& erase(unsigned int strart_id, unsigned int end_id)" << endl;str = "Hello_World_Welcome";cout << "str.erase(6, 10)->" << str.erase(6, 10) << endl;str = "Hello_World_Welcome";cout << "str.erase(8, 13)->" << str.erase(8, 13) << endl;cout << "############################" << endl << endl;str = "Hello_World_Welcome";iter = str.erase(str.begin()+5);cout << "after str.erase(str.begin()+5) -> " << str << endl << "return iter -> " << *iter << endl;str = "Hello_World_Welcome";iter = str.erase(str.end()-10);cout << "after str.erase(str.end()-10) -> " << str << endl << "return iter -> " << *iter << endl;cout << "############################" << endl << endl;
查看运行结构