在STL容器有序排序 [英] Ordered sort in STL containers
问题描述
抱歉,如果这个问题标题术语是错的,但这里是我想要做,我需要的物体的向量进行排序,但与一的 的典型的比较小于的方法我需要重新排名,基于某些字符串ID属性的对象,以使每个相同类型构件定位在连续的顺序像这样的:
Sorry if the question title terminology is wrong, but here is what I want to do.I need to sort a vector of objects, but contrary to a typical comparison "less than" approach I need to re-position the objects based on some string ID property so that each same type members are positioned in consecutive order like this:
[id_town,id_country,id_planet,id_planet,id_town,id_country]
变成这样的:
becomes this:
[id_town,id_town,id_country,id_country,id_planet,id_planet]
ID_属性字符串。
id_ property is string.
推荐答案
的std ::排序
具有可用于传递一个布尔值predicate,作为自定义比较第三个参数。 编写您自己比较acording您的规格和使用它。
例如:
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:
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; } );
最后,你也可以重载比较操作符(运营商GT;
和运营商的LT;
),并使用所提供的比较标准库如 的std ::更大
:
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 );
}
这篇关于在STL容器有序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!