STL函数对象
2019-03-08 本文已影响0人
Jianbaozi
#include "../std_lib_facilities.h"
struct Record {
string firstname;
char* lastname;
Record(string s, char* p) :firstname(s), lastname(p) {}
void print() { cout << firstname << " " << lastname <<'\n'; }
};
bool f(Record& r) { return r.firstname == "Diana"; } //函数当作参数传递
struct cmp_fname { //函数对象
bool operator()(const Record& a,const Record& b)const
{
return a.firstname < b.firstname;
}
};
/*struct cmp_lname {
bool operator()(const Record& a, const Record& b)const
{
return strncmp(a.lastname, b.lastname,20) < 0;
}
};*/
bool cmp_lname(const Record& a, const Record& b)
{
return strncmp(a.lastname, b.lastname, 20) < 0;
}
int main(){
vector<Record> vr = {
Record{"Arthur","Curry"},
Record{"Barry","Allen"},
Record{"Diana","Prince"},
Record{"Clark","Kent"}
};
cout << "sort by first name:" << '\n';
cout << "--------------------------" << '\n';
sort(vr.begin(), vr.end(), cmp_fname()); //注意 cmp_fname()括号
for (auto r : vr)
r.print();
cout <<'\n'<< "sort by last name:" << '\n';
cout << "--------------------------" << '\n';
sort(vr.begin(), vr.end(), cmp_lname);
for (auto r : vr)
r.print();
cout << "--------------------------" << '\n';
auto p=find_if(vr.begin(), vr.end(), f); //做参数时不要加(),会变成函数调用
cout << "position " << p - vr.begin() + 1 << endl;
system("pause");
return 0;
}
输出:
sort by first name:
--------------------------
Arthur Curry
Barry Allen
Clark Kent
Diana Prince
sort by last name:
--------------------------
Barry Allen
Arthur Curry
Clark Kent
Diana Prince
--------------------------
position 4
请按任意键继续. . .