programmer.h
<code>#ifndef PRO
<code>#define PRO
<code>#include<iostream>
<code>#include<algorithm>
<code>#include<set>
<code>#include<functional>
<code>#include<string>
<code>using namespace std;
<code>class Programmer {
public:
Programmer(const size_t id, const wstring& name) :Name(name), Id(id) { }
const wstring& GetName()const { return Name; };
const size_t GetId()const { return Id; }
void Print() const {
wcout << L"[" << Id << L"]::" << Name << endl;
}
Programmer& SetName(const wstring& s)
{
Name = s;
return this;
}
private:
wstring Name;
int Id = 0;
};
class ProgrammerNameGreater : public binary_function<Programmer, Programmer, bool> {
public:
bool operator()(const Programmer& p1, const Programmer& p2)
{
return (p1.GetName() < p2.GetName());
}
};
class ProgrammerIdGreater : public binary_function<Programmer, Programmer, bool> {
public:
bool operator()(const Programmer& p1, const Programmer& p2)
{
return (p1.GetId() > p2.GetId());
}
};
<p>programmer.cpp
<code>#endif // !PRO
<code>#include<iostream>
<code>#include<algorithm>
<code>#include<set>
<code>#include<functional>
<code>#include<string>
<code>#include"programmer.h"
<code>using namespace std::placeholders;
<code>using namespace std;
<code>int main()
{
set<Programmer, ProgrammerIdGreater> set1;
set1.insert({ Programmer(1,L"Scott Meyers"),
Programmer(2,L"Martin Fowler"),
Programmer(3,L"Bill Gates"),
Programmer(4,L"P.J Plaught"),
Programmer(5,L"StanLey B.Lippman"),
Programmer(6,L"Andrei Alexandrescu") });//(1)
for_each(set1.begin(), set1.end(), mem_fn(&Programmer::Print)); //(2)
set<Programmer, ProgrammerIdGreater>::iterator it = set1.find(Programmer(3, L"Bill Gates"));//(3)
if (it == set1.end())
cout << "No find" << endl;
else
{
const_cast<Programmer&>(it).SetName(L"David Vandevoorde"); //(4)
}cout << "_______________________________________________________________" << endl;
for_each(set1.begin(), set1.end(), mem_fn(&Programmer::Print)); //(5)
set<Programmer, ProgrammerNameGreater> set2 (set1.begin(), set1.end());
cout << "_______________________________________________________________" << endl;
for_each(set2.begin(),set2.end(),bind(&Programmer::Print,_1)/mem_fun_ref(&Programmer::Print)/); //(6)
}
<p>在(5)中和(6)都是对
f(x); //
语法#1:当f是一个非成员函数
x.f(); //
语法#2:当f是一个成员函数,而且x是一个对象或一个对象的引用
p->f(); //
语法#3:当f是一个成员函数,而且p是一个对象的指针
这三种情况的处理通过mum_fn或bind把*.和->.无法直接处理的对象改为可以处理的。
网友评论