我正在尝试按多列对矢量进行排序。所以继承我的矢量,其中行是行数。因为我在for-loop中使用不同大小的向量,所以它必须是动态的。
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
答案 0 :(得分:4)
由于您希望基于前两列进行排序,因此compare函数需要使用这两个值。另外,将compare
的返回类型更改为bool
以及const&
的参数类型。
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];
}