按多列对Vecor进行排序

Sorting Vecor by multiple columns

本文关键字:排序 Vecor      更新时间:2023-10-16

我正在尝试按多列对向量进行排序。这就是我的向量,这里的行数是行数。因为我在for循环中使用不同大小的向量,所以它必须是动态的。

vector<vector<double> > matrix;
matrix.resize(rows);
for(size_t i=0; i<rows; i++) {
    matrix[i].resize(3);
}

向量设置好后,我用数据填充它。数据由坐标(xyz)组成。

for(size_t i = 0;i<lss.size();i+2) {
            int k = i+1;
            matrix[i][0]=lss[i].v[0].x;
            matrix[i][1]=lss[i].v[0].y;
            matrix[i][2]=lss[i].v[0].z;
            matrix[k][0]=lss[i].v[1].x;
            matrix[k][1]=lss[i].v[1].y;
            matrix[k][2]lss[i].v[1].z;
    }

到目前为止一切都很好。但接下来我必须对向量进行排序。我从我的数据中知道,对于一个循环段落,z坐标总是相同的。所以我必须根据向量的第一列和第二列对其进行排序。我已经在搜索排序函数,比如std:sort,但找不到合适的函数。我的尝试是:

int compare(vector<double>& s1, vector<double>& s2)
{
    return s1[0] < s2[0];
}   
std::sort(matrix.begin(), matrix.end(), compare);

但结果与输入相同。

因此,未排序的输出如下所示:

X=-5.000000, Y=2.000000, Z=-2.000000
X=-5.000000, Y=-5.000000, Z=-2.000000
X=5.000000, Y=5.000000, Z=-2.000000
X=5.000000, Y=-2.000000, Z=-2.000000
X=5.000000, Y=-2.000000, Z=-2.000000
X=5.000000, Y=-5.000000, Z=-2.000000
X=5.000000, Y=5.000000, Z=-2.000000
X=2.000000, Y=5.000000, Z=-2.000000
X=2.000000, Y=5.000000, Z=-2.000000
X=-5.000000, Y=5.000000, Z=-2.000000
X=5.000000, Y=-5.000000, Z=-2.000000
X=-2.000000, Y=-5.000000, Z=-2.000000
X=-2.000000, Y=-5.000000, Z=-2.000000
X=-5.000000, Y=-5.000000, Z=-2.000000

我想要的是:

X=-5.000000, Y=-5.000000, Z=-2.000000
X=-5.000000, Y=-5.000000, Z=-2.000000
X=-5.000000, Y=2.000000, Z=-2.000000
X=-5.000000, Y=5.000000, Z=-2.000000
X=-2.000000, Y=-5.000000, Z=-2.000000
X=-2.000000, Y=-5.000000, Z=-2.000000
X=2.000000, Y=5.000000, Z=-2.000000
X=2.000000, Y=5.000000, Z=-2.000000
X=5.000000, Y=-5.000000, Z=-2.000000
X=5.000000, Y=-5.000000, Z=-2.000000
X=5.000000, Y=-2.000000, Z=-2.000000
X=5.000000, Y=-2.000000, Z=-2.000000
X=5.000000, Y=5.000000, Z=-2.000000
X=5.000000, Y=5.000000, Z=-2.000000

由于要根据前两列进行排序,compare函数需要同时使用这两个值。另外,将返回类型compare更改为bool并且参数类型为CCD_ 3。

bool compare(vector<double> const& s1, vector<double> const& s2)
{
    // If the values of the first column are not equal,
    // just use them to order s1 and s2.
    if ( s1[0] != s2[0] )
    {
       return s1[0] < s2[0];
    }
    // If the values of the first column are equal,
    // use the values of the second column to order s1 and s2.
    return s1[1] < s2[1];
}