按多个因素对表进行排序
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::tuple
或boost::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
的谓词使用它。
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 如何在C++中对数组进行冒泡排序