user1683894
user1683894

Reputation: 425

Sorting multidimensional arrays in c++ using STL methods

i was wondering if there are any means by which we can sort multidimensional arrays using STL in c++. i wanted to try using STL methods because they will be best in competitions instead of writing our own sorting algorithm. i tried a pseudo-code which is buggy and i don't know how to handle the error.

int a[n][n];

//read values into array

for(i=0;i<n;i++)
{
sort(a[i][0],a[i][n]);
}

Upvotes: 1

Views: 2275

Answers (3)

Vikas Choudhary
Vikas Choudhary

Reputation: 1

instead of using sort(a[i][0],a[i][n]);
use sort(a[i],a[i]+n);
it will work.

Upvotes: 0

The Vivandiere
The Vivandiere

Reputation: 3201

More generic is to use Boost Multi-Arrays. MultiArrays allow you to specify ranges of all sorts, that you can then feed into std::sort, depending on what subset of the 2D array you want to sort.

http://www.boost.org/doc/libs/1_56_0/libs/multi_array/doc/user.html#sec_views

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 118011

It depends how you want to sort. First of all, I would recommend using std::vector. Then use std::sort. By default, it will sort by the first element of each vector. See the following example.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::vector<int>> a = {{1,5,4,3},
                                       {2,5,1,4},
                                       {1,1,6,2}};

    std::sort(begin(a), end(a));  // Sort a by the first element of each vector

    for (auto& line : a)   // Loop over each inner vector
    {
        for (auto& element : line)  // Loop over each element in current vector
        {
            std::cout << element;
        }
        std::cout << std::endl;
    }
    return 0;
}

Output

1162
1543
2514

Alternatively, you can go through each vector and sort by it's elements

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::vector<int>> a = {{1,5,4,3},
                                       {2,5,1,4},
                                       {1,1,6,2}};

    for (auto& line : a)   // Loop over each inner vector
    {
        std::sort(begin(line), end(line));  // Sort each vector
        for (auto& element : line)  // Loop over each element in current vector
        {
            std::cout << element;
        }
        std::cout << std::endl;
    }
    return 0;
}

Output

1345
1245
1126

Upvotes: 3

Related Questions