Home > Blockchain >  How can I sort a 2D vector in C by the first and second index?
How can I sort a 2D vector in C by the first and second index?

Time:04-28

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}}

CodePudding user response:

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 << " ";            
}

Live sample

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 << " ";
}

Live sample

Output:

1 100 10 22 10 24 10 25 10 26 13 12

CodePudding user response:

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;
    });

CodePudding user response:

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;
}

CodePudding user response:

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;
} 
  • Related