【问题标题】:how to std::sort a 3 dimensional vector如何对 3 维向量进行 std::sort 排序
【发布时间】:2013-07-01 18:00:26
【问题描述】:

我有一个向量声明如下:

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 ),我试图将它作为一个独立的 2d 向量排序并且只有 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 上使用它 我会得到 ​​p>

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}

【问题讨论】:

  • 首先,您必须考虑对您而言,一个向量大于另一个向量意味着什么。在示例中,您只提供了第一个坐标很重要。那么——你的情况应该如何?
  • 我如何看到这个向量是 6 个表相互叠加,x 最多 200000,y 最多 7,z 最多 6。我想在一个排序命令中进行排序基于第 5 个值的 7 个值的 y“行”。最大值应为 x =0,最小值应为 x = 200000
  • 好的,但是当一个向量不相等时,更大,小于另一个? IE。 (1,2,3)(1,3,2) 大吗?
  • 发布一个数字示例,因为我不确定您将要做什么和实现什么。
  • 我是否理解正确,您想在不更改这些矩阵的情况下对(在本例中)148995 2D 矩阵的向量进行排序,并希望根据 M[5][n] 的值对它们进行排序,其中 n是一个可以从排序更改为排序的参数吗?

标签: c++ sorting vector multidimensional-array


【解决方案1】:

您应该使用 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);

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

【讨论】:

  • dhaveniths 的答案更加详尽,并且正在使用 C++11。原则上它们是相同的。我希望你现在了解 std::sort 的使用。
【解决方案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]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多