Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading