Home > Article > Backend Development > How to Sort a Vector of User-Defined Types by Specific Variables?
Sort User-Defined Types in a Vector by Specific Variables
In order to sort a vector of user-defined types by a specific variable, you have two options: using the standard library sort or implementing your own sort function.
Using the Standard Library Sort
The standard library sort can be used if your user-defined type implements the "bool operator < (const Type& other) const" and a copy constructor. The comparison operator should define a meaningful way to compare the types. Here's an example:
struct MyType { int a; int b; bool operator<(const MyType& other) const { // Compare types based on a specific variable (e.g., a) return a < other.a; } };
Using a Custom Sort Function
Alternatively, you can provide a custom ordering function or functor as the third argument to sort() instead of implementing the comparison operator. This function should compare the types based on the desired variable. For instance:
bool type_is_less(const MyType& t1, const MyType& t2) { return t1.a < t2.a; } std::sort(moo.begin(), moo.end(), type_is_less);
This approach is useful when:
The above is the detailed content of How to Sort a Vector of User-Defined Types by Specific Variables?. For more information, please follow other related articles on the PHP Chinese website!