Home >Backend Development >C++ >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!