排序自定义对象的向量 [英] Sorting a vector of custom objects
问题描述
如何对包含自定义(即用户定义)对象的向量进行排序。
可能,标准STL算法排序与谓词(函数或应该使用在自定义对象中的一个字段(作为排序的键)上操作的函数对象(例如,函数对象)。
是在正确的轨道上吗?
使用 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指出,不是提供排序谓词,您可以覆盖<
中的运算符:
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);
}
};
使用此方法意味着您可以按如下方式对向量进行排序:
std :: sort(vec.begin(),vec.end());
Edit2:由于Kappa建议你也可以order by override> operator并改变调用排序位:
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 as:
std :: sort(vec.begin(),vec.end(),greater< MyStruct>());
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?解决方案A simple example using
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());
Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can override the < operator in
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: As Kappa suggests you can also sort the vector in the descending order by override > 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); } };
And you should call sort as:
std::sort(vec.begin(), vec.end(),greater<MyStruct>());
这篇关于排序自定义对象的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!