I was wondering how in C++ I could sort a 2D vector so that it is sorted by both elements. It would be sorted in ascending order by the first element, and if there are multiple of the first element, they will be sorted by ascending order of the second element. Here is an example of what I mean:
vector<vector<int>> vec = {{10, 23}, {10, 22}, {1, 100}, {13, 12}};
this would get sorted into:
{{1, 100}, {10, 22}, {10, 23}, {13, 12}}
>Solution :
If you are using C++20 std::ranges::sort would be a good option:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<std::vector<int>> vec = {{10, 25}, {10, 23}, {10, 22},
{10, 24}, {1, 100}, {13, 12}};
std::ranges::sort(vec);
for (const auto& row : vec)
for (const auto& col : row)
std::cout << col << " ";
}
Output:
1 100 10 22 10 23 10 24 10 25 13 12
If not std::sort works just as well:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> vec = {{10, 25}, {10, 22}, {10, 26},
{10, 24}, {1, 100}, {13, 12}};
std::sort(vec.begin(), vec.end());
for (const auto& row : vec)
for (const auto& col : row)
std::cout << col << " ";
}
Output:
1 100 10 22 10 24 10 25 10 26 13 12