一、概念
仿函数就是一个使用起来像是函数的对象。是在一个类中,operator重载(),该类的对象使用该函数时,就像是一个函数一样。
二、实例代码
template<class T>
class Less {
public:
bool operator()(const T& x, const T& y) const
{
return x < y;
}
};
void test()
{
Less<int> func;
cout << func(1, 2) << endl;
cout << func.operator()(1, 2) << endl;
cout << Less<int>()(1, 2) << endl;//匿名对象
cout << less<int>().operator()(1, 2) << endl;//匿名对象
}
class goods {
public:
goods(string goodsname,float price,float score)
:_goodsname(goodsname),
_price(price),
_score(score)
{}
//获取商品名
string Get_goodsname() const
{
return _goodsname;
}
//获取价格
float Get_price() const
{
return _price;
}
//获取评分
float Get_score() const
{
return _score;
}
private:
string _goodsname;//商品名
float _price;//价格
float _score;//评分
};
class goods_price_less {
public:
bool operator()(const goods& x, const goods& y)//仿函数:低价优先
{
return x.Get_price() < y.Get_price();
}
};
class goods_price_greater {
public:
bool operator()(const goods& x, const goods& y)//仿函数:高价优先
{
return x.Get_price() > y.Get_price();
}
};
class goods_score_less {
public:
bool operator()(const goods& x, const goods& y)//仿函数:低分优先
{
return x.Get_score() < y.Get_score();
}
};
class goods_score_greater {
public:
bool operator()(const goods& x, const goods& y)//仿函数:高分优先
{
return x.Get_score() > y.Get_score();
}
};
void test()
{
vector<goods> v;
v.push_back({ "苹果", 3.2, 3.8 });
v.push_back({ "香蕉", 2.2, 4.2 });
v.push_back({ "西瓜", 0.9, 4.9 });
for (auto& e : v)
{
cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
}
cout << endl;
cout << "低价优先" << endl;
sort(v.begin(), v.end(), goods_price_less());
for (auto& e : v)
{
cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
}
cout << endl;
cout << "高价优先" << endl;
sort(v.begin(), v.end(), goods_price_greater());
for (auto& e : v)
{
cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
}
cout << endl;
cout << "低分优先" << endl;
sort(v.begin(), v.end(), goods_score_less());
for (auto& e : v)
{
cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
}
cout << endl;
cout << "高分优先" << endl;
sort(v.begin(), v.end(), goods_score_greater());
for (auto& e : v)
{
cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
}
cout << endl;
}