如何在保持主要排序的同时执行次要排序
How do you perform a secondary sort while maintaining a primary sort
例如,我正在编写一个包含条目(字符串键、整数计数)的散列 table。首先,我进行选择排序以按计数对每个条目进行排序。然后我想在保持排序计数的同时按字母顺序对它们进行排序。有办法吗?
这里是初级排序。
void MyTrends::sortByCount(Entry* arr, int sizeOfArray) {
int maxIndex; // the index of the element that has the highest count
for(int i=0; i < sizeOfArray-1; i++){
maxIndex = i;
for(int j=i+1; j < m; j++){
if(arr[j].getCount() > arr[maxIndex].getCount()){ //if the count of element j is higher than the count of the Entry at the current max index then change the max index to j
maxIndex = j;
}
}
if (maxIndex != i) {
Entry temp = arr[i]; //next 2 lines + this line are swapping max to first position and old first position to the position the max was in
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
}
}
}
编辑:经过更多思考,这是否可以通过先按字母顺序排序然后使用 stable 排序按计数排序来完成?
您需要的是自定义 Entry
比较运算符。例如
struct Entry {
int num;
char letter;
}
bool operator< (const Entry& lhs, const Entry& rhs)
{
if ( lhs.num == rhs.num )
return lhs.letter < rhs.letter;
else
return lhs.num < rhs.num;
}
然后使用自定义比较对其进行排序。该列表将首先按数字(num
成员)排序,然后使用 letter
成员按字母顺序排序。
struct Entry {
int num;
char letter;
friend auto make_tie(Entry const&e){
return std::tie(e.num,e.letter);
}
friend bool operator<(Entry const&lhs, Entry const& rhs){
return make_tie(lhs)<make_tie(rhs);
}
};
这利用了 tuple
的 lexographic 排序来排序您的条目。 tie
创建一个引用元组。
它需要写 make_tie
,但是一旦你有了它,你就可以免费获得 ==
<
,你也可以将它用于其他一些功能——序列化,打印,swap
,等等
make_tie
是 C++14——对于 C++11,您需要在 [=13= 的 )
和 {
之间添加一个 ->decltype(std::tie(e.num,e.letter))
].
例如,我正在编写一个包含条目(字符串键、整数计数)的散列 table。首先,我进行选择排序以按计数对每个条目进行排序。然后我想在保持排序计数的同时按字母顺序对它们进行排序。有办法吗?
这里是初级排序。
void MyTrends::sortByCount(Entry* arr, int sizeOfArray) {
int maxIndex; // the index of the element that has the highest count
for(int i=0; i < sizeOfArray-1; i++){
maxIndex = i;
for(int j=i+1; j < m; j++){
if(arr[j].getCount() > arr[maxIndex].getCount()){ //if the count of element j is higher than the count of the Entry at the current max index then change the max index to j
maxIndex = j;
}
}
if (maxIndex != i) {
Entry temp = arr[i]; //next 2 lines + this line are swapping max to first position and old first position to the position the max was in
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
}
}
}
编辑:经过更多思考,这是否可以通过先按字母顺序排序然后使用 stable 排序按计数排序来完成?
您需要的是自定义 Entry
比较运算符。例如
struct Entry {
int num;
char letter;
}
bool operator< (const Entry& lhs, const Entry& rhs)
{
if ( lhs.num == rhs.num )
return lhs.letter < rhs.letter;
else
return lhs.num < rhs.num;
}
然后使用自定义比较对其进行排序。该列表将首先按数字(num
成员)排序,然后使用 letter
成员按字母顺序排序。
struct Entry {
int num;
char letter;
friend auto make_tie(Entry const&e){
return std::tie(e.num,e.letter);
}
friend bool operator<(Entry const&lhs, Entry const& rhs){
return make_tie(lhs)<make_tie(rhs);
}
};
这利用了 tuple
的 lexographic 排序来排序您的条目。 tie
创建一个引用元组。
它需要写 make_tie
,但是一旦你有了它,你就可以免费获得 ==
<
,你也可以将它用于其他一些功能——序列化,打印,swap
,等等
make_tie
是 C++14——对于 C++11,您需要在 [=13= 的 )
和 {
之间添加一个 ->decltype(std::tie(e.num,e.letter))
].