c++ - 按第二列对向量进行排序
问题描述
我正在尝试vector<vector<int>>
按第二列对 a 进行排序。
问题所在的函数:
bool SortSecCol( const vector<int>& v1,const vector<int>& v2 )
{
return v1[1] < v2[1];
}
void SortingSearch(domain &d)
{
for (auto &pos : d.Position) // Check if bound limits has changed. If so, adjust bound limits.
{
d.lb = min(d.lb, pos - d.delta * 0.5);
d.ub = max(d.ub, pos + d.delta * 0.5);
}
vec3<double> length = d.ub - d.lb; // calculate length of domain
double c_size = d.kappa * d.h; // set cell size = kappa * eta * h_initial
vec3<long> c_n = cast<long>(ceil(length / c_size)); // determine number of cells in each direction
std::vector<std::vector<long>> c_pidx; // cell particle index array
c_pidx.resize(c_n.x * c_n.y * c_n.z); // resize cell array and initialise to 0
for (long i=0, imax=d.Position.size(); i<imax; ++i) // for each particle position:
{
vec3<long> c_pos = cast<long>(floor((d.Position[i] - d.lb) / c_size)); // determine cell position
long c_idx = cell_idx(c_pos, c_n); // determine cell index
c_pidx[c_idx].emplace_back(i); // store particle index in cell
d.ParticleCellID[i].emplace_back(i);
d.ParticleCellID[i].emplace_back(c_idx);
}
sort(d.ParticleCellID.begin(), d.ParticleCellID.end(), SortSecCol);
// Displaying the 2D vector after sorting
std::cout << "The Vector after sorting is:\n";
for (int i=0; i<d.ParticleCellID.size(); i++)
{
for (int j=0; j<2 ;j++)
{
std::cout << d.ParticleCellID[i][j] << " ";
}
std::cout << std::endl;
}
}
问题是向量在此之后以原始顺序返回未排序。我不确定我在这里缺少什么。
该向量很长(16K 行,每行 2 列),其中一部分是:
356 41
357 47
358 42
359 23
当我排序输出与输入完全相同
虽然我想做的是:
359 23
356 41
358 42
357 47
我还创建了这个来检查它,在这里它工作得很好。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> VectorToSort{{0,11},{1,7},{2,8},{3,18}};
bool SortSecCol( const vector<int>& v1,const vector<int>& v2 )
{
return v1[1] < v2[1];
}
int main()
{
sort(VectorToSort.begin(), VectorToSort.end(), SortSecCol);
// Displaying the 2D vector after sorting
std::cout << "The Vector after sorting is:\n";
for (int i=0; i<VectorToSort.size(); i++)
{
for (int j=0; j<2 ;j++)
{
std::cout << VectorToSort[i][j] << " ";
}
std::cout << std::endl;
}
}
输出:
1 7
2 8
0 11
3 18
解决方案
您在上面发布的代码应该可以工作并做您想做的事情,假设d.ParticleCellID
包含向量,其中至少有 2 个元素。否则元素访问操作符(operator[])SortSecCol
会抛出异常
推荐阅读
- javascript - 将 axios 请求的响应推送到数组中
- codeigniter - Codeigniter中的内部连接与多个表
- angular - Angular Subject 不听变化
- c++ - 无法使用 fstream 从二进制文件中读取字符串,而是显示奇怪的符号
- python - 在python中匹配之前添加文本2行
- python - 即使我的 MQTT 客户端未连接,我如何继续运行我的程序?
- php - If 语句不显示 else 结果
- typescript - 如何根据条件将可选属性设置为必需?
- node.js - 任何redis调用的ioredis发送命令的默认超时是多少
- c - 对于我的 C 代码,我正在读取一个文件并对其进行排序,这给了我垃圾输出。为什么?