Home  >  Article  >  Backend Development  >  How to Sort a Vector of User-Defined Types by Specific Variables?

How to Sort a Vector of User-Defined Types by Specific Variables?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 01:36:02158browse

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:

  • You cannot or do not want to implement the comparison operator.
  • You need to sort built-in or pointer types that cannot be overloaded.
  • You want to sort the sequence using different criteria at different times.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn