练习题目:
struct Programmer{
Programmer(const int id, const std::wstring name):
Id(id), Name(name){ }
void Print() const
{
std::wcout<<L"["<<Id<<L"]: "<<Name<<std::endl;
}
int Id;
std::wstring Name;
};
//2, 定义仿函数
//a, 使用ID升序排序
struct ProgrammerIdGreater : public std::binary_function< Programmer, Programmer, bool>{
bool operator() (const Programmer& p1, const Programmer& p2) const {
return (key1 <= key2) ? false : true;
}
};
//b, 使用Name来进行排序
struct ProgrammerNameComparer : public std::binary_function< Programmer, Programmer, bool>{
bool operator() (const Programmer& p1, const Programmer& p2) const {
return (p1.GetId() <= p2.GetId()) ? false : true;
}
};
void main()
{
//构建数组
Programmer vp[6] = {
Programmer("Andrei", 6),
Programmer("Stanley", 5),
Programmer("Plaught", 4),
Programmer("BillGates", 3),
Programmer("Fowler", 2),
Programmer("Meyes", 1)
};
//构建set
std::set<Programmer, ProgrammerIdGreater > dest(vp, vp+6);
//遍历set
std::for_each( dest.begin(), dest.end(), std::mem_fun(&Programmer::Print) );
//将dest中的BillGates改为David
std::set<Programmer, ProgrammerIdGreater>::iterator it = dest.find(Programmer("BillGates", 3));
if(it != dest.end())
const_cast<Programmer&>(*it).SetName("David");
//遍历set
std::for_each( dest.begin(), dest.end(), std::mem_fun(&Programmer::Print) );
//新set2用名字排序
std::set<Programmer, ProgrammerNameComparer > dest2(dest, dest+6);
//遍历set2
std::for_each( dest2.begin(), dest2.end(), std::mem_fun(&Programmer::Print) );
}