按多个因素对表进行排序

Sorting a table by multiple factors

本文关键字:排序      更新时间:2023-10-16

所以我在这种情况下,我必须写一个类来排序元素表。我想只对列进行排序但我想进行多级排序例如

a 2
b 1
b 2
a 1

第一个排序将在第一列上,并以如下方式结束

a 2
a 1
b 1
b 2

现在我想对第二列进行排序而不打乱第一列的排序就像这样

a 1
a 2
b 1
b 2

我的想法是,对于每一级排序,我都要跟踪需要排序的范围。所以在初始排序之前,我的范围是这样的:range = 0..3,然后下一级是range=0..1,2..3。我不确定这是否会非常有效,所以我想征求一下其他方法的意见。

编辑:我需要取任意数量的列,可能为每个列使用自定义比较器

您可以将每一行存储在std::pair<char, int>中,将它们放在std::vector<std::pair<char, int>>中,并使用std::sort函数为您提供所需的排序。你不需要自己编写任何类或算法。

std::vector<std::pair<char, int>> table;
// read data into `table`
....
// sort the table
std::sort(table.begin(), table.end());
// print out contents
for (const auto& p : table)
{
  std::cout << p.first << " " << p.last << "n";
}

可以通过使用std::tuple(或std::tr1::tupleboost::tuple,如果您坚持使用旧的c++实现)将其推广到更多列。tuples具有与pair相同的字典比较方式。如果您需要不同的排序,您可以将自己的比较函数作为第三个参数传递给std::sort

下面是一个例子

#include <iostream>
#include <algorithm>
#include <iterator>
#include <utility>
int main() 
{
    std::pair<char, int> a[] = 
    { 
        { 'a', 2 },
        { 'b', 1 },
        { 'b', 2 },
        { 'a', 1 }
    };
    for ( const auto &p : a )
    {
        std::cout << p.first << 't' << p.second << std::endl;
    }
    std::cout << std::endl;
    std::sort( std::begin( a ), std::end( a ) );
    for ( const auto &p : a )
    {
        std::cout << p.first << 't' << p.second << std::endl;
    }
    return 0;
}

输出为

a   2
b   1
b   2
a   1
a   1
a   2
b   1
b   2

代替std::pair,您可以对多个列使用std::tuple。例如

#include <iostream>
#include <algorithm>
#include <iterator>
#include <tuple>
int main() 
{
    std::tuple<char, int, bool> a[] = 
    { 
        std::make_tuple( 'a', 2, true ),
        std::make_tuple( 'b', 1, false ),
        std::make_tuple( 'b', 2, true ),
        std::make_tuple( 'a', 1, true ),
        std::make_tuple( 'a', 2, false ),
        std::make_tuple( 'a', 1, false )
    };
    for ( const auto &t : a )
    {
        std::cout << std::get<0>( t ) << 't' 
                  << std::get<1>( t ) << 't'
                  << std::get<2>( t ) << std::endl;
    }
    std::cout << std::endl;
    std::sort( std::begin( a ), std::end( a ) );
    for ( const auto &t : a )
    {
        std::cout << std::get<0>( t ) << 't' 
                  << std::get<1>( t ) << 't'
                  << std::get<2>( t ) << std::endl;
    }
    return 0;
}

输出为

a   2   1
b   1   0
b   2   1
a   1   1
a   2   0
a   1   0
a   1   0
a   1   1
a   2   0
a   2   1
b   1   0
b   2   1

如果你必须排序的结构数组与不同的数据成员,那么你可以从这些数据成员建立一个元组,并在std::sort的谓词使用它。