抱歉,如果问题标题术语有误,但这是我想做的。我需要对对象 vector 进行排序,但与 typical comparison 相反“小于”方法我需要根据一些字符串 ID 属性重新定位对象,以便每个相同类型的成员都按这样的连续顺序定位:
[id_town,id_country,id_planet,id_planet,id_town,id_country]
变成这样:
[id_town,id_town,id_country,id_country,id_planet,id_planet]
id_ 属性为字符串。
最佳答案
std::sort
有第三个参数,可用于传递充当自定义比较器的 bool 谓词。 根据您的规范编写自己的比较器并使用它。
例如:
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 );
}
此外,在 C++11 中,您可以使用 lambda:
std::sort( std::begin(v) , std::end(v) , [](const foo& lhs , const foo& rhs) { return lhs.id < rhs.id; } );
最后,您还可以重载比较运算符(operator>
和operator<
)并使用标准库提供的比较器,例如 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 );
}
关于c++ - STL 容器中的有序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18659882/