本文内容学习自 Scott Meyers的《Effective C++》“第33条:对包含指针的容器使用remove这一类算法时要特别小心”
remove搭配erase
容器(除了list)中的remove不是真正意义上的删除。因为它做不到。
remove仅仅是把想要移动的对象放到容器的后面,不需要替换的元素不断从后面移动、替换前面需要被删除的元素。
vector<int>::iterator newEnd( remove(v.begin(), v.end(), 99) );
remove和erase可以实现真正的删除。
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
v.push_back( 3 );
v.push_back( 99 );
v.push_back( 5 );
v.push_back( 99 );
v.push_back( 7 );
v.push_back( 8 );
v.push_back( 9 );
v.push_back( 99 );
vector<int>::iterator newEnd( remove( v.begin(), v.end(), 99 ) );
v.erase( newEnd, v.end() );
for( auto it: v )
{
cout << it << "\t";
}
cout << endl;
装载指针的容器删除元素
如果容器内部是指针(不包括智能指针),那么删除元素就需要仔细,避免内存泄露。
通常需要先释放指针所指向的内存,然后再删除元素(指针)
例如:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Widget
{
public:
Widget(const int _value){ value = _value; }
bool isCertified(){ return value != 0; }
int GetValue(){ return value; }
private:
int value;
};
void delUncertified( Widget* &pWidget )
{
if( !pWidget->isCertified() )
{
delete pWidget;
pWidget = nullptr;
}
}
int main(int argc, char *argv[])
{
vector<Widget*> v;
for( int i = 0; i < 5; ++i )
{
v.push_back( new Widget( i ) );
}
for_each( v.begin(), v.end(), delUncertified );
v.erase( remove( v.begin(), v.end(), static_cast<Widget*>(0) ), v.end() );
for( auto it: v )
{
cout << it->GetValue() << "\t";
}
cout << endl;
return 0;
}