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
Release: 2024-12-10 22:35:11
Original
655 people have browsed it

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;
    }
};
Copy after login

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

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

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;
});
Copy after login

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);
    }
};
Copy after login

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

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

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!

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