首页 > 解决方案 > 按第二列对向量进行排序

问题描述

我正在尝试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 

标签: c++sorting

解决方案


您在上面发布的代码应该可以工作并做您想做的事情,假设d.ParticleCellID包含向量,其中至少有 2 个元素。否则元素访问操作符(operator[])SortSecCol会抛出异常


推荐阅读