0

I have a 3D array where I keep 3 columns of numeric data. I want to sort this Nx3 matrix in ascending order, by first column, then for the cases where the values are the same on this column, I want them to be sorted according to second column.

For example: If there are multiple of min elements in column 1, I want so sort them furthermore by second column, again in ascending order. So it would look like this:

[1, 2, 3]
[1, 3, 1]
[2, 4, 2]
[3, 5, 6]

etc.

Since there were multiple of min element "1" in column 1, furthermore sorting is carried out for these min values of column 1, according to column 2 values.

I know this was possible in Pandas of Python but is there any convenient way to do this in C++?

2
  • Write a custom comparator that will do what you need. See, for example, this question. Commented Dec 7, 2019 at 18:30
  • Is this about a 2 dimensional array (where the first dimension happens to be of size 3) or am I missing something? Commented Dec 7, 2019 at 18:47

1 Answer 1

1

I would try the standard algorithm std::sort() with a comparator which is specific to your need.
( https://en.cppreference.com/w/cpp/algorithm/sort )

/*
  g++ -std=c++17 -o prog prog.cpp \
      -pedantic -Wall -Wextra -Wconversion \
      -g -O0 -fsanitize=address,undefined
*/

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

struct Vec3
{
  int x, y, z;
};

int
main()
{
  auto v=std::vector<Vec3>{{3, 5, 6},
                           {2, 4, 2},
                           {1, 3, 1},
                           {1, 2, 3}};
  const auto show=
    [&]()
    {
      for(const auto &e: v)
      {
        std::cout << e.x << ' ' << e.y << ' ' << e.z << '\n';
      }
    };
  show();
  std::sort(begin(v), end(v),
    [&](const auto &lhs, const auto &rhs)
    {
      if(lhs.x<rhs.x) return true;
      if(lhs.x>rhs.x) return false;
      if(lhs.y<rhs.y) return true;
      if(lhs.y>rhs.y) return false;
      return lhs.z<rhs.z;
    });
  std::cout << "~~~~~~~~~~~~~~~~\n";
  show();
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.