Reputation: 139
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}}
Upvotes: 1
Views: 2192
Reputation: 23792
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
Upvotes: 1
Reputation: 79208
sort(vec.begin(), vec.end(), [&](vector<int> &a, vector<int> &b){
return a[0] < b[0]? true : (a[0] == b[0]) ? a[1] < b[1] : false;
});
Upvotes: 1
Reputation: 66
I thought this was pretty cool when I saw it. Using a compare function to std::sort, you could write something like below. This extends quite nicely and is pretty flexible on nested orderings!
bool comp(vector<int> v1, vector<int> v2)
{
if(v1[0]<v2[0])
return true;
else if(v1[0]==v2[0])
return v1[1]<v2[1];
else
return false;
}
Upvotes: 0
Reputation: 19
like this :
int m = vec.size();
int n = vec[0].size();
sort(vec[0].begin(), vec[0].end());
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << vec[i][j] << " ";
cout << endl;
}
Upvotes: 0