In C , we can encounter situations where we need to sort a vector of pairs based on the second element. Let's explore how to achieve this effortlessly using the provided information.
The provided vector of pairs, vec, holds pairs of integers and we want to sort it in ascending order based on the second element of each pair. Without resorting to custom function objects, let's leverage the standard template library (STL) and std::less to do the job.
The easiest solution in C 14 leverages lambdas with parameter type inference:
std::sort(vec.begin(), vec.end(), [](auto &left, auto &right) { return left.second < right.second; });
This anonymous lambda captures the left and right pairs and returns true if the second element of left is less than that of right, effectively sorting the vector in ascending order.
If lambdas are not an option, we can define a custom comparator to handle the sorting:
struct sort_pred { bool operator()(const std::pair<int, int> &left, const std::pair<int, int> &right) { return left.second < right.second; } }; std::sort(vec.begin(), vec.end(), sort_pred());
The sort_pred struct implements the comparison operator, comparing the second elements of the two pairs and returning true if the left pair's element is less than the right.
To generalize the comparator and reuse it for sorting, we can create a template:
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); } };
With this template, we can now sort using:
std::sort(vec.begin(), vec.end(), sort_pair_second<int, int>());
By providing the template arguments, we specify the types of the pair elements and can even customize the comparison using a different predicate like std::greater for descending order.
The above is the detailed content of How to Sort a Vector of Pairs in C Based on the Second Element?. For more information, please follow other related articles on the PHP Chinese website!