Для сортировки массива пар в C++ можно использовать различные методы. Вот несколько часто используемых подходов:
-
Использование функции
sort()с пользовательским компаратором:#include <iostream> #include <algorithm> #include <vector> bool comparePairs(const std::pair<int, int>& a, const std::pair<int, int>& b) { return a.first < b.first; // Sort based on the first element of the pair } int main() { std::vector<std::pair<int, int>> pairs = {{2, 5}, {1, 3}, {4, 2}}; std::sort(pairs.begin(), pairs.end(), comparePairs); for (const auto& pair : pairs) { std::cout << pair.first << " " << pair.second << std::endl; } return 0; } -
Использование лямбда-функции с функцией
sort():std::sort(pairs.begin(), pairs.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b) { return a.first < b.first; // Sort based on the first element of the pair }); -
Использование пользовательского функтора с функцией
sort():struct PairComparator { bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) { return a.first < b.first; // Sort based on the first element of the pair } }; std::sort(pairs.begin(), pairs.end(), PairComparator());
Эти методы позволяют сортировать массив пар по первому элементу каждой пары. Вы можете изменить логику сравнения для сортировки по второму элементу или любому другому критерию.