erase()是STL提供的容器中比較常用的方法之一,它的功能是刪除容器中的某些元素,其中它的函數原型如下:
1.有兩個參數,且參數類型都是size_t型:
string& erase ( size_t pos = 0, size_t n = npos );
功能是:刪除容器中從pos位置開始的n個元素。返回值是經過刪除操作后的容器。
示例:
#include<iostream> using namespace std; int main() { string str = "hello world!"; string::iterator it_1 = str.begin(); string::iterator it_2 = str.begin() + 1; //用法1 cout<<str.erase(0,1)<<endl; }
結果:
(注:第一種erase用法是string容器所特有的,vectro和list等容器沒有這種用法,更多erase的用法見:http://www.cplusplus.com/search.do?q=erase)
2.有一個參數,且參數類型為iterator:
iterator erase ( iterator position );
功能是:刪除容器中position所指位置的元素。返回值是指向被刪元素之后的那個元素(即下一個元素)的迭代器。
示例:
#include<iostream> using namespace std; int main() { string str = "hello world!"; string::iterator it_1 = str.begin(); string::iterator it_2 = str.begin() + 1; //用法2 str.erase(it_1); cout<<str<<endl; }
結果:
3.有兩個參數,且參數類型都是iterator:
iterator erase ( iterator first, iterator last );
功能是:刪除容器中first到last之間的所有元素(左閉右開),但不包括last所指的元素。(即刪除fist~last -1所指的元素)返回值是一個迭代器,該迭代器指向last所指得的元素,可以理解為返回的就是last。
示例:
#include<iostream> using namespace std; int main() { string str = "hello world!"; string::iterator it_1 = str.begin(); string::iterator it_2 = str.begin() + 1; //用法3 str.erase(it_1,it_2); cout<<str<<endl; }
結果: