#include <vector>
#include <algorithm>
#include <iostream>
int main( ) {
using namespace std;
vector <int> v1;
vector <int>::iterator Iter1, Iter2, new_end;
int i;
for ( i = 0 ; i <= 9 ; i++ )
v1.push_back( i );
int ii;
for ( ii = 0 ; ii <= 3 ; ii++ )
v1.push_back( 7 );
random_shuffle ( v1.begin( ), v1.end( ) );
cout << "Vector v1 is ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl; //输出结果:Vector v1 is ( 7 1 9 2 0 7 7 3 4 6 8 5 7 7 )
// Remove elements with a value of 7
new_end = remove ( v1.begin( ), v1.end( ), 7 ); //移除容器中所有值为7的元素,但这一算法并不真正从容器中删除这些元素(换句话说容器大小并未改变),而是将每个不与7相等的值轮番begin()后面的空间。返回值标示出重新整理后最后一个元素的下一个位置。从返回值的位置到end()中的数据为残留数据,其值仍为原来的值。
cout << "Vector v1 with value 7 removed is ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl; //输出结果:Vector v1 with value 7 removed is ( 1 9 2 0 3 4 6 8 5 6 8 5 7 7 ).
// To change the sequence size, use erase
v1.erase (new_end, v1.end( ) ); //删除残留数据
cout << "Vector v1 resized with value 7 removed is ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl; //输出结果:Vector v1 resized with value 7 removed is ( 1 9 2 0 3 4 6 8 5 ).
}
总结,要删除容器中值等于给定值的元素,可采用如下方法:
v.erase(remove(v.begin(),v.end,value),v.end()); //其中v为容器对象,value为给定的值。
注:erase为成员函数, remove为STL库函数,需要头文件<algorithm>。