# 2.使用STL中通用算法或容器成员函数删除元素的方法

0        1        2        3         3       4  移除前

0        1        2        4         3       4  移除后

5

void main() {

vector<int> vectInt;

int i;

for (i = 0; i < 5; i++ ) {

vectInt.push_back( i );

if ( 3 == i ) {

vectInt.push_back( i );

}

}

remove( vectInt.begin(), vectInt.end(), 3 );

cout << " after deleted , size = " << vectInt.size() << endl;

for ( i = 0; i < vectInt.size();; i++ ) {

cout << "i = " << i << " , " << vectInt[i] << endl;

}

}

after deleted , size = 6 // 从这行可以看出，移除后容器的大小没变

i = 0 , 0

i = 1 , 1

i = 2 , 2

i = 3 , 4 //  从这行可以看出：“应被删除的元素” 3 被其后的“未被删除的元素” 4 覆盖

i = 4 , 3

i = 5 , 4

6

void main() {

vector<int> vectInt;

int i;

for (i = 0; i < 5; i++ ) {

vectInt.push_back( i );

if ( 3 == i ) {

vectInt.push_back( i );

}

}

vectInt.erase( remove( vectInt.begin(), vectInt.end(), 3 ), vectInt.end() );

cout << " after deleted , size = " << vectInt.size() << endl;

for ( i = 0; i < vectInt.size();; i++ ) {

cout << "i = " << i << " , " << vectInt[i] << endl;

}

}

after deleted , size = 4 // 从这行可以看出，删除后容器的大小变化了

i = 0 , 0

i = 1 , 1

i = 2 , 2

i = 3 , 4

7

#include <iostream>

#include <sstream>

#include <string>

#include <vector>

#include <algorithm>

#include <list>

using namespace std;

class CTest {

public:

CTest( const string& str, int iPrice ) : m_strName( str ), m_iPrice( iPrice ) { }

void vPrint() { cout << "name=" << m_strName << " price = " << m_iPrice << endl;

}

private:

string m_strName;

int   m_iPrice;

//     由于两个函数对象要访问 CTest 类的 private 成员，所以设为友员。

friend class CStrFunc;

friend class CIntFunc;

};

//     函数对象，根据 string 比较

class CStrFunc {

string m_str;

public:

CStrFunc( const string& str ) : m_str( str ) {

}

bool operator() ( const CTest& left ) {

return ( m_str == left.m_strName ) ? true : false;

}

};

//     函数对象，根据 int 比较

class CIntFunc {

int m_iPrice;

public:

CIntFunc( int iPrice ) : m_iPrice( iPrice ) {

}

bool operator() ( const CTest& left ) {

return ( m_iPrice == left.m_iPrice ) ? true : false;

}

};

void main( ) {

vector< CTest > vectTest;

int i;

for (  i = 0; i < 5 ; i++ ) {

stringstream stream; //       流格式化符，把 int 转化为 string

stream << i;

string str = stream.str();

CTest clTest( str, i );

vectTest.push_back( clTest );

}

for (  i = 0 ; i < vectTest.size(); i++ )  {

vectTest[ i ].vPrint();

}

//     删除所有 m_strName = "3" 的元素

vectTest.erase( remove_if( vectTest.begin(), vectTest.end(), CStrFunc( "3" ) ),

vectTest.end() );

cout << "delete 3 after : " << endl;

for (  i = 0 ; i < vectTest.size(); i++ )  {

vectTest[ i ].vPrint();

}

//     删除所有

• 本文已收录于以下专栏：

举报原因： 您举报文章： STL序列式容器中删除元素的方法和陷阱二 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)