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

How Can I Sort a Vector of Pairs Based on the Second Element in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 22:35:11722browse

How Can I Sort a Vector of Pairs Based on the Second Element in C  ?

Sorting Vectors of Pairs Using the Second Element

Sorting vectors of pairs based on the second element is a common programming task. This article explores various methods to accomplish this using existing STL components and std::less.

Method 1: Custom Comparator

A custom comparator is a common approach. Create a struct with an overridden operator() function that compares pairs based on their second elements. For example:

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

Then, call sort() with this comparator as the third argument:

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

Method 2: Lambda Expression (C 11)

In C 11, you can use a lambda expression to define the comparison function:

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

Method 3: Generic Template-Based Comparator (C 11)

For reusable code, create a generic 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);
    }
};

Then, call sort() with this template-based comparator:

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

Recommendation

For reusability, the generic template-based comparator is a powerful option. However, for simplicity, writing a custom comparator or lambda expression is often sufficient.

The above is the detailed content of How Can I 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