C++ vector数组实现多级排序—使用sort()函数

之前有记录过 python 使用 numpy 的多级排序方法:

numpy 多级排序 :lexsort 函数详解_地球被支点撬走啦的博客-CSDN博客_lexsort

C++ 多级排序可以借用 sort() 函数(在头文件 <algorithm> 中)的第三个参数实现。

比如实现一个 6*3 的 vector 数组的多级升序排序(三级)的话,可以首先编写下面这个逻辑比较规则函数:

// 升序多级排序,此时的判断条件是 < 号
bool my_compare(vector<int> a, vector<int> b)
{
    if(a[0] != b[0]) return a[0] < b[0];   // 第一级比较
    else
    {
        if(a[1]!=b[1]) return a[1] < b[1]; // 如果第一级相同,比较第二级
        else return a[2] < b[2];           // 如果第二级仍相同,比较第三级
    }
}

如果想实现降序排序,将函数中的 < 号改为 > 号即可。

将该函数名作为 sort() 的第三个参数传入即可,使用方式如下:

int main()
{
    vector<vector<int>> arr = {
   
   {3, 6, 3}, 
                               {6, 0, 9}, 
                               {3, 2, 5}, 
                               {7, 9, 6}, 
                               {7, 3, 3}, 
                               {3, 2, 1}};
    sort(arr.begin(), arr.end(), my_compare);
    for(auto e : arr)
    {
        for(auto i:e) cout << i << " ";
        cout << endl;
    }
    return 0;
}
/* 输出 *
3 2 1 
3 2 5
3 6 3
6 0 9
7 3 3
7 9 6
*********/

注意:

如果是在类中定义逻辑比较函数,需要在将函数声明为 static 类型,否则会报如下错误:

error: reference to non-static member function must be called

原因是:sort() 函数的第三个参数代表的函数的参数列表中不允许有指针参数,而类中如果成员函数没有声明为static,C++会默认给成员函数添加一个this指针。对于本例就是类似下面这样的:

bool my_compare(ClassName *this, vector<int> a, vector<int> b)

猜你喜欢

转载自blog.csdn.net/Flag_ing/article/details/126556211