0

我有一个声明如下的向量:

vector<vector<vector<int> > > myVector (148995,vector<vector<int> >(7,vector <int>(6,0)));

我希望能够使用 std::sort 对其进行排序。

我想通过 Myvector[x][y][z] 中 y = 5 的值对 y 的所有值进行排序

我希望能够一次对一个 z 进行排序(z 值可以从 0 到 5 ),我试图将它排序为一个独立的二维向量并且只有 Myvector[x][y] 但我总是得到编译这样做时出错。

我在另一个适用于 2d 矢量的 stackoverflow 问题上找到了此代码,但我有限的编程技能不允许我将其转换为 3d 矢量:

std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){ return a[1] > b[1]; } );

谢谢你,凯文

编辑

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}

如果我按 y = 5 的值对所有 x 的 myvector[x][y][z] 进行排序,并对 z = 0 的所有 'y' 值进行排序(z 可以从 0 变为 5)

如果我要使用我想要的排序并在 z = 0 上使用它,我会得到

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}
4

2 回答 2

2

我不确定我是否正确理解了这个问题,但是如果您只想对每个矩阵的整数元素 M[y][z] 上的矩阵向量进行排序,那么我认为您需要以下代码:

#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]
}
于 2013-07-03T21:53:56.253 回答
2

您应该使用 std::sort 和用于排序的函数。如果我理解正确,您想根据第 2 或第 3 维进行排序。

bool comparison_function(const std::vector<std::vector<int> >& v1, 
                         const std::vector<std::vector<int> >& v2) {
  // calculate some comparison_result
  return comparison_result
}

使用此函数,您可以调用 std::sort:

std::sort(myVector.begin(), myVector.end(), comparison_function);

如果您的比较相当复杂,那么您应该使用仿函数而不是 compare_function 来注入状态。

于 2013-07-03T22:03:18.930 回答