按多列对Vecor进行排序
Sorting Vecor by multiple columns
我正在尝试按多列对向量进行排序。这就是我的向量,这里的行数是行数。因为我在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];
}
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 按多列对Vecor进行排序