Home > Backend Development > C++ > How to Efficiently Sort a Vector of Pairs by the Second Element?

How to Efficiently Sort a Vector of Pairs by the Second Element?

Linda Hamilton
Release: 2024-12-09 13:47:24
Original
974 people have browsed it

How to Efficiently Sort a Vector of Pairs by the Second Element?

How to Efficiently Sort a Vector of Pairs by Pair's Second Element

This article addresses the question of sorting a vector of pairs based on the second element of each pair in ascending order. While creating a custom function object for this task is a viable solution, there are alternative methods that utilize existing STL components and std::less.

Using std::sort with a Custom Comparator

One approach is to employ a custom comparator as an optional third argument to std::sort. This custom comparator, called sort_pred, is defined as follows:

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

To utilize this comparator, simply pass it to std::sort:

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

Using C 11 Lambdas

If using a C 11 compiler, you can leverage lambdas in place of a custom comparator:

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

Using a Generic Template for Pair Sorting

For greater flexibility and reusability, you can create a generic template called sort_pair_second:

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

With this template, you can achieve the desired sorting as follows:

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

The above is the detailed content of How to Efficiently Sort a Vector of Pairs by the Second Element?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template