Home >Backend Development >C++ >How to Custom Sort a Vector of Pairs Based on the Second Element in C ?

How to Custom Sort a Vector of Pairs Based on the Second Element in C ?

DDD
DDDOriginal
2024-12-13 12:12:10502browse

How to Custom Sort a Vector of Pairs Based on the Second Element in C  ?

Custom Sorting of Vectors of Pairs

Consider the scenario where you want to sort a vector of pairs (

std::vector<std::pair<int, int>>
) based on the second element of each pair in increasing order.

To achieve this without implementing a separate function object, you can utilize the third parameter of

std::sort
, which accepts a custom comparator. This comparator compares two pairs based on their second elements using the provided comparator.

For example, using a C 11 compiler, you can define a comparator with a lambda expression:

std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
    return left.second < right.second;
});

Alternatively, define a custom struct that overloads the

operator()
function to perform the comparison:

struct sort_pred {
    bool operator()(const std::pair<int,int>& left, const std::pair<int,int>& right) {
        return left.second < right.second;
    }
};

std::sort(v.begin(), v.end(), sort_pred());

If you desire a generic solution that can be reused with different types and comparators, create a template like this:

template <class T1, class T2, class Pred = std::less<T2>>
struct sort_pair_second {
    bool operator()(const std::pair<T1,T2>& left, const std::pair<T1,T2>& right) {
        Pred p;
        return p(left.second, right.second);
    }
};

With this template, you can sort pairs using any custom comparator:

std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

The above is the detailed content of How to Custom Sort a Vector of Pairs Based on the Second Element in C ?. 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