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都是迭代器)
下面给你一个例子:// vector_erase.cpp // compile with: /EHsc #include <vector> #include <iostream> int main( ) { using namespace std; vector <int> v1; vector <int>::iterator Iter; v1.push_back( 10 ); v1.push_back( 20 ); v1.push_back( 30 ); v1.push_back( 40 ); v1.push_back( 50 ); cout << "v1 =" ; for ( Iter = v1.begin( ) ; Iter != v1.end( ) ; Iter++ ) cout << " " << *Iter; cout << endl; v1.erase( v1.begin( ) ); cout << "v1 ="; for ( Iter = v1.begin( ) ; Iter != v1.end( ) ; Iter++ ) cout << " " << *Iter; cout << endl; v1.erase( v1.begin( ) + 1, v1.begin( ) + 3 ); cout << "v1 ="; for ( Iter = v1.begin( ) ; Iter != v1.end( ) ; Iter++ ) cout << " " << *Iter; cout << endl; }
输出结果:v1 = 10 20 30 40 50
v1 = 20 30 40 50
v1 = 20 50
C++中string erase函数的使用
最新推荐文章于 2022-02-15 14:53:13 发布