Reputation: 137
I have a vector declared as follow :
vector<vector<vector<int> > > myVector (148995,vector<vector<int> >(7,vector <int>(6,0)));
I would like to be able to use std::sort to sort it.
I want to sort all the value of y by the value of y = 5 in Myvector[x][y][z]
I would like to be able to sort one z at a time (z value can be from 0 to 5 ), i have tried to sort it as an independent 2d vector and only have Myvector[x][y] but I always get compile error while doing so.
I have found this code on another stackoverflow question that works for 2d vector but my limited programming skills do not let me convert it for a 3d vector :
std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){ return a[1] > b[1]; } );
thank you, Kaven
edit
myVector[x][y][z]
Myvector[x] = {0,1,2,3,...,200 000}
myvector[0][y][0] = {44,30,21,15,1,600,25}
myvector[1][y][0] = [25,24,10,7,1,700,30}
myvector[0][y][2] = {34,20,11,6,1,400,25}
myvector[1][y][2] = [33,24,10,7,1,300,40}
if i would sort myvector[x][y][z] for all x by the value of y = 5 and sort all 'y' values where z = 0 (z can change from 0 to 5)
if i were to use the sort i would like and use it on z = 0 i would get
myvector[1][y][0] = {44,30,21,15,1,600,25}
myvector[0][y][0] = [25,24,10,7,1,700,30}
myvector[0][y][2] = {34,20,11,6,1,400,25}
myvector[1][y][2] = [33,24,10,7,1,300,40}
Upvotes: 0
Views: 2543
Reputation: 2048
I'm not sure I understand the question correctly, but if all you want is to sort a vector of matrices on the integer element M[y][z] of each matrix then I think the following code is what you need:
#include <vector>
#include <algorithm>
using namespace std;
using Row = vector<int>;
using Matrix = vector<Row>;
using Matrices = vector<Matrix>;
/// Sort a vector of matrices on element M[y][z] of each of the matrices.
/// terminology: y and z as in original question
void sort_on( Matrices &matrices, int y, int z)
{
sort(
matrices.begin(), matrices.end(),
[y,z](const Matrix &lhs, const Matrix &rhs)
{
return lhs[y][z] < rhs[y][z];
});
}
int main()
{
Matrices myVector( 100000, Matrix( 7, Row(6,0)));
sort_on( myVector, 5, 0); // sort on M[5][0]
sort_on( myVector, 5, 5); // sort on M[5][5]
}
Upvotes: 2
Reputation: 880
You should be using std::sort and a function you use for sorting. If I understand you correctly you want to sort based on the 2nd or 3rd dimension.
bool comparison_function(const std::vector<std::vector<int> >& v1,
const std::vector<std::vector<int> >& v2) {
// calculate some comparison_result
return comparison_result
}
Using this function you can call std::sort:
std::sort(myVector.begin(), myVector.end(), comparison_function);
If your comparisons are rather complex then you should use functors instead of the comparison_function to inject state.
Upvotes: 2