Home > Article > Backend Development > Can Standard Library Sort Handle Sorting User-Defined Types?
Sorting User-Defined Types with Standard Library Sort
Sorting a vector of user-defined types (UDTs) by a specific member variable is a common task. The standard library sort function can perform this operation if certain criteria are met.
Can Standard Library Sort Handle UDT Sorting?
Yes, standard library sort can be utilized to arrange UDTs based on a member variable. This requires two key elements:
Example with Operator Overload:
struct MyType { int a; int b; bool operator<(const MyType& other) const { // Custom comparison logic based on 'a' } };
Example with Custom Ordering Function:
You can also pass a custom ordering function as an argument to sort() instead of implementing the operator <:
bool compareMyType(const MyType& t1, const MyType& t2) { // Custom comparison logic based on 'a' }
In either case, you can sort your UDT vector using:
std::sort(moo.begin(), moo.end()); // for operator overload std::sort(moo.begin(), moo.end(), compareMyType); // for custom function
Note that the comparison logic (based on a) should be consistent with the sorting order you desire (e.g., lowest to highest, highest to lowest).
The above is the detailed content of Can Standard Library Sort Handle Sorting User-Defined Types?. For more information, please follow other related articles on the PHP Chinese website!