#include <iostream>
#include <algorithm>
#include <map>
#include <iterator>
#include <functional>
#include <sstream>
#include <vector>
using namespace std;
class Widget
{
private:
int weight;
public:
Widget()
{
};
Widget(int val);
Widget& operator=(int val);
friend ostream& operator<<(ostream &os,Widget w);
bool isCertified();
};
Widget::Widget(int val)
{
weight=val;
}
Widget& Widget::operator=(int val)
{
this->weight=val;
return *this;
}
ostream& operator<<(ostream &os,Widget w)
{
os<<w.weight;
return os;
}
bool Widget::isCertified()
{
return this->weight>=10;
}
class Derefence
{
public:
template<typename T>
const T& operator()(const T *w)
{
return *w;
}
};
void delAndNullifyUncertified(Widget* &w)
{
if(!w->isCertified())
{
delete w;
w=nullptr;
}
}
int main()
{
vector<Widget*> vec;
for(int i=1;i<=10;i++)
{
vec.push_back(new Widget(2*i+1));
}
//涉及到指针的erase-remove可能会造成内存泄漏
//vec.erase(remove_if(vec.begin(),vec.end(),not1(mem_fun(&Widget::isCertified))),vec.end());
//先删除不合格的数据,把指针置空
for_each(vec.begin(),vec.end(),delAndNullifyUncertified);
vec.erase(remove(vec.begin(),vec.end(),static_cast<Widget*>(0)),vec.end());
transform(vec.begin(),vec.end(),ostream_iterator<Widget>(cout," "),Derefence());
return 0;
}
对包含指针的容器使用remove要特别小心
最新推荐文章于 2021-03-01 11:26:33 发布