1

I have a 2d vector array which contains :

row id   r   b   main  
   1     0   26   3
   2     1   11   2
   3     1   46   4
   4     2   26   1
   5     3   11   2

I want to sort every row based on its "main"-column value smaller "main"-column. smaller value => the entire row should be on the top.

if there is tow rows or more and there "main"-column have the same value, I want to check "r"-column. smaller value => the entire row should be on the top.

after sorting it will look like this:

row id   r   b   main  
   4     2   26   1
   2     1   11   2
   5     3   11   2
   1     0   26   3
   3     1   46   4

1 Answer 1

3

Try using std::sort like

using int_arr = std::array<int, 4>;
std::sort(std::begin(arr), std::end(arr), [](const int_arr& a, const int_arr& b){
    return a[3] != b[3] ? a[3] < b[3] : a[1] < b[1];
});

Demo

#include <iostream>
#include <array>
#include <algorithm>

int main() {
    using int_arr = std::array<int, 4>;
    int_arr arr[5] = { 
        {1, 0, 26, 3}, 
        {2, 1, 11, 2}, 
        {3, 1, 46, 4}, 
        {4, 2, 26, 1}, 
        {5, 3, 11, 2}
    };

    for(const auto& i_arr : arr) {
        for(const auto& i : i_arr)
            std::cout<< i <<", ";
        std::cout << "\n";
    }

    std::cout << "**************\n";

    std::sort(std::begin(arr), std::end(arr), [](const int_arr& a, const int_arr& b){
        return a[3] != b[3] ? a[3] < b[3] : a[1] < b[1];
    });

    for(const auto& i_arr : arr) {
        for(const auto& i : i_arr)
            std::cout<< i <<", ";
        std::cout << "\n";
    }
}

OutPut

1, 0, 26, 3, 
2, 1, 11, 2, 
3, 1, 46, 4, 
4, 2, 26, 1, 
5, 3, 11, 2, 
**************
4, 2, 26, 1, 
2, 1, 11, 2, 
5, 3, 11, 2, 
1, 0, 26, 3, 
3, 1, 46, 4,
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.