我正在尝试按第二列对vector<vector<int>>
进行排序。
问题所在的函数:
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
答案 0 :(得分:0)
假设d.ParticleCellID
包含向量(其中至少包含2个元素),您上面发布的代码应该可以工作并做您想要的事情。
否则SortSecCol
中的元素访问运算符(operator [])将引发异常
答案 1 :(得分:0)
好的,问题是我只是使用vector.reserve(number)保留了向量的内存。当我将其大小调整为我使用vector.resize()拥有的粒子数时,一切运行正常。