函数对象理解:
- C++中,只要实现了operator()的类或者结构体,都可以称为函数对象
struct SortUser {
bool operator()(const CoreUser& u1, const CoreUser& u2) {
return u1.cost < u2.cost;
}
};
class find_billion{
private:
char country[20];
int agebegin, ageend;
public:
find_billion(const char *_country, int _agebegin, int _ageend){
strcpy(country, _country);
agebegin = _agebegin;
ageend = _ageend;
}
void operator() (const billion * tbin){
if(strcmp(tbin->country,this->country))
return;
if(tbin->age < agebegin || tbin->age > ageend)
return;
cout<<setw(5)<<tbin -> no;
cout<<setw(20)<<tbin -> name;
cout<<setw(20)<<tbin -> account;
cout<<setw(2)<<tbin -> age;
cout<<setw(20)<<tbin -> company;
cout<<setw(20)<<tbin -> country;
}
};
通过对 ( )的运算符重载来实现对函数的调用
- 实例化
std::for_each()
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn)
{
while (first!=last) {
fn (*first);
++first;
}
return fn; // or, since C++11: return move(fn);
}
std::sort()与之类似
//select one:
SortUser sortuser;
sort(v.begin(), v.end(),sortuser);
//select two:
sort(v.begin(), v.end(),SortUser());
以上两种方法都可用,
select1、很显然实例化一个结构体对象sortuser,sortuser进入sort(),会执行sort()函数里的fn(*first,*first+1)即sortuser(*v.begin(),*v.begin+1),sortuser()的()为结构体SortUser中的operator().
select2、SortUser()为构造函数,SortUser()会实现实例化一个函数对象,之后就相当于sortuser了。
for_each(bin.begin(), bin.end(), find_billion("China", 38, 45));
.为了方便理解,便设了一个find_billion()的构造函数.