问题描述
如何对包含自定义(即用户定义)对象的向量进行排序.
可能应该使用标准 STL 算法排序以及谓词(函数或函数对象),该谓词将对自定义对象中的一个字段(作为排序的键)进行操作.
我在正确的轨道上吗?
How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a function or a function object) which would operate on one of the fields (as a key for sorting) in the custom object should be used.
Am I on the right track?
推荐答案
一个使用 的简单示例std::sort
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};
struct less_than_key
{
inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
{
return (struct1.key < struct2.key);
}
};
std::vector < MyStruct > vec;
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
std::sort(vec.begin(), vec.end(), less_than_key());
正如 Kirill V. Lyadvinsky 指出的,您可以为 MyStruct
实现 operator<
,而不是提供排序谓词:
As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the operator<
for MyStruct
:
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator < (const MyStruct& str) const
{
return (key < str.key);
}
};
使用此方法意味着您可以简单地按如下方式对向量进行排序:
Using this method means you can simply sort the vector as follows:
std::sort(vec.begin(), vec.end());
Edit2:正如 Kappa 建议的,您还可以通过重载 >
运算符并稍微更改排序调用来按降序对向量进行排序:
As Kappa suggests you can also sort the vector in the descending order by overloading a >
operator and changing call of sort a bit:
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator > (const MyStruct& str) const
{
return (key > str.key);
}
};
你应该调用 sort 为:
And you should call sort as:
std::sort(vec.begin(), vec.end(),greater<MyStruct>());
这篇关于对自定义对象的向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!