std::sort
has a third parameter which can be used to pass a boolean predicate that acts as custom comparator. Write your own comparator acording to your specifications and use it.
For example:
struct foo
{
std::string id;
foo(const std::string& _id) : id( _id ) {}
};
//Functor to compare foo instances:
struct foo_comparator
{
operator bool(const foo& lhs , const foo& rhs) const
{
return lhs.id < rhs.id;
}
};
int main()
{
std::vector<foo> v;
std::sort( std::begin(v) , std::end(v) , foo_comparator );
}
Also, in C++11 you could use a lambda:
std::sort( std::begin(v) , std::end(v) , [](const foo& lhs , const foo& rhs) { return lhs.id < rhs.id; } );
Finally, you can also overload the comparison operators (operator>
and operator<
) and use comparators provided by the standard library like std::greater
:
struct foo
{
std::string id;
foo(const std::string& _id) : id( _id ) {}
friend bool operator<(const foo& lhs , const foo& rhs)
{
return lhs.id < rhs.id;
}
friend bool operator>(const foo& lhs , const foo& rhs)
{
return rhs < lhs;
}
friend bool operator>=(const foo& lhs , const foo& rhs)
{
return !(lhs < rhs);
}
friend bool operator<=(const foo& lhs , const foo& rhs)
{
return !(lhs > rhs);
}
};
int main()
{
std::vector<foo> v;
std::sort( std::begin(v) , std::end(v) , std::greater );
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…