Reputation: 1504
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++?
Upvotes: 0
Views: 539
Reputation: 16805
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;
}
Upvotes: 1