Home >Backend Development >C++ >How to Sort Vectors of Pairs Based on Their Second Elements in C ?

How to Sort Vectors of Pairs Based on Their Second Elements in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 21:48:14551browse

How to Sort Vectors of Pairs Based on Their Second Elements in C  ?

Sorting Vectors of Pairs Based on Second Elements

Given a vector of pairs, one may wish to arrange them in ascending order based on their second elements. While constructing custom function objects accomplishes this task, let's explore whether the Standard Template Library (STL) empowers us with more convenient methods.

Using a Custom Comparator

The third parameter of std::sort allows for a custom comparator function to be specified. We can define one as follows:

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());

Using Lambdas in C 11 and Up

In C 11 and later versions, lambdas offer a compact alternative:

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

Leveraging Templates for Flexibility

For increased reusability, one can define a template-based comparator:

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);
    }
};

This allows for even greater flexibility:

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

The above is the detailed content of How to Sort Vectors of Pairs Based on Their Second Elements 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