How to sort a std::vector of std::pairs

Sort a std::vector<std::pair<...>> in-place by the first element of the pair:

sort_by_first.cpp
std::sort(ret.begin(), ret.end(), [](const auto& a, const auto& b) {
    return a.first < b.first;
});

Sort a std::vector<std::pair<...>> in-place by the second element of the pair:

sort_by_second.cpp
std::sort(ret.begin(), ret.end(), [](const auto& a, const auto& b) {
    return a.second < b.second;
});

 


Check out similar posts by category: C/C++