std::set的comparator写法
实际上看了一些别人的资料http://www.cppblog.com/xmli/archive/2008/09/08/61282.html,写得很好。文中的代码也是转载的
总结一下,两种写法:
1 写set中元素的<构造符,但必须要求是const。猜想是因为set中对元素可能会有再继承或者封装处理,默认的比较函数是const operator<,所以必须要求const
bool operator<(const Country& b)const
{
return m_nPopulation<b.m_nPopulation;
}
2 单独写一个comparator,写一个新的函数类(结构也是类),并完成operator()函数,不要求const
//设计函数对象
struct country_less:public std::binary_function<Country, Country, bool>
{
//这个倒不必须成为const成员函数,呵呵
bool operator()(const Country& a, const Country& b)const
{
return a.GetPopulation()<b.GetPopulation();
}
};
//std::set的定义就要复杂一些了
std::set<Country, country_less> countrySet;
//同样,迭代器的定义也要复杂一些
for (std::set<Country, country_less>::iterator iter=countrySet.begin(); countrySet.end()!=iter; ++iter)
{
iter->print();
}