Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort 2d C++ array by first element in subarray

I am trying to sort a c++ subarray by first element. My code is currently set up like this:

int umbrellas[3][2] = {{5, 6}, {2, 7}, {9, 20}};

int n = sizeof(umbrellas) / sizeof(umbrellas[0]);

sort(umbrellas, umbrellas + n, greater<int>());

The sort function doesn't seem to be functioning properly and when I run the code it generates errors. Is there a way to sort the array from

{{5, 6}, {2, 7}, {9, 20}}

into

{{2, 7}, {5, 6}, {9, 20}}

?

like image 229
Redz Avatar asked Mar 12 '26 17:03

Redz


1 Answers

Use a std::vector of std::vector as your container and the sort becomes much easier to do with. Not only is std::vector the preferred container for C++ but using STL functions on it is way simpler and direct , without any substantiable overhead.

Define your data as

std::vector<std::vector<int>> umbrellas{
    {5, 6},
    {2, 7},
    {9, 20}
};

Now you can use a custom comparator lambda that takes in two vector element references and returns True when the first element of the above vector is smaller than that of the one below.

std::sort(umbrellas.begin(),
          umbrellas.end(),
          [](const std::vector<int> &above, const std::vector<int> &below)
          {
              return (above[0] < below[0]);
          });

And the output :

for (auto &&row : umbrellas) {
    for (auto element : row) {
        std::cout<< element<< " ";
    }
    std::cout<< "\n";
}
2 7 
5 6 
9 20

Taking this to C++20 it's even easier:

std::ranges::sort(umbrellas, std::less(),
     [](const auto &v) { return v[0];});
like image 91
TheMedicineSeller Avatar answered Mar 14 '26 06:03

TheMedicineSeller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!