C++ STL容器中的有序排序
如果问题标题术语错误,很抱歉,但我想做的是这样的。我需要对对象向量进行排序,但与“小于”的方法相反,我需要根据某个字符串ID属性重新定位对象,以便每个相同类型的成员按如下顺序连续定位:C++ STL容器中的有序排序,c++,algorithm,C++,Algorithm,如果问题标题术语错误,很抱歉,但我想做的是这样的。我需要对对象向量进行排序,但与“小于”的方法相反,我需要根据某个字符串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_uu属性是string。有第三个参数,可用于传递充当
[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_uu属性是string。有第三个参数,可用于传递充当自定义比较器的布尔谓词根据您的规格编写自己的比较器并使用它。
例如:
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 );
}
具有第三个参数,可用于传递充当自定义比较器的布尔谓词根据您的规格编写自己的比较器并使用它。
例如:
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 );
}
std::sort
将比较谓词作为其第三个参数。只需编写一个合适的id。所有这些id都在容器中吗?id是容器中对象的属性。std::sort
将比较谓词作为其第三个参数。只要写一个合适的。所有这些id都在容器中吗?这些id是容器中对象的属性。@MichaelIV注意,实用程序库提供了基于operator==
和operatorGreat的所有关系运算符的实现!谢谢曾经阅读过有关函子的内容,但从未意识到它们有多有用。@MichaelIV您不必包含(使用
语句)std::rel_ops
名称空间,因为重载会被发现,您不应该传递对象而不是类吗?也就是说,sort(begin(v)、end(v)、foo_comparator())
@MichaelIV注意,实用程序库提供了基于operator==
和operatorGreat!谢谢曾经阅读过有关函子的内容,但从未意识到它们有多有用。@MichaelIV您不必包含(使用
语句)std::rel_ops
名称空间,因为重载会被发现,您不应该传递对象而不是类吗?也就是说,sort(begin(v)、end(v)、foo_comparator())
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 );
}