snippetcppCritical
How do I sort a vector of custom objects?
Viewed 0 times
howsortobjectsvectorcustom
Problem
How does one go about sorting a
Probably, you can use the standard library algorithm
Am I on the right track?
std::vector containing custom (i.e. user-defined) objects?Probably, you can use the standard library algorithm
std::sort along with a predicate (a function or a function object) which would operate on one of the data members (as a key for sorting) in the custom object.Am I on the right track?
Solution
A simple example using
Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the
And you should call sort as:
std::sortstruct 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 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 implement the
operator 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());Code Snippets
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());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());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(),greater<MyStruct>());Context
Stack Overflow Q#1380463, score: 457
Revisions (0)
No revisions yet.