C++ 如何在维护主排序的同时执行辅助排序
例如,我正在编写一个包含条目(字符串键、int计数)的哈希表。首先,我做一个选择排序,按计数对每个条目进行排序。然后我想在保持排序计数的同时按字母顺序对它们进行排序。有办法做到这一点吗 这是主要的分类C++ 如何在维护主排序的同时执行辅助排序,c++,sorting,selection,C++,Sorting,Selection,例如,我正在编写一个包含条目(字符串键、int计数)的哈希表。首先,我做一个选择排序,按计数对每个条目进行排序。然后我想在保持排序计数的同时按字母顺序对它们进行排序。有办法做到这一点吗 这是主要的分类 void MyTrends::sortByCount(Entry* arr, int sizeOfArray) { int maxIndex; // the index of the element that has the highest count for(int i=0; i <
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;
}
}
}
void MyTrends::sortByCount(条目*arr,int-sizeOfArray){
int maxIndex;//具有最高计数的元素的索引
对于(int i=0;iarr[maxIndex].getCount()){//
maxIndex=j;
}
}
if(maxIndex!=i){
Entry temp=arr[i];//接下来的两行+这一行将最大值切换到第一个位置,将旧的第一个位置切换到最大值所在的位置
arr[i]=arr[maxIndex];
arr[maxIndex]=温度;
}
}
}
编辑:仔细考虑后,是否可以先按字母顺序排序,然后使用稳定的排序按计数排序?您需要的是一个自定义的
条目
比较运算符。例如
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;
}
struct条目{
int-num;
字符字母;
}
bool操作员<(常数输入和左侧、常数输入和右侧)
{
如果(lhs.num==rhs.num)
返回左侧字母<右侧字母;
其他的
返回lhs.num
然后使用自定义比较对其进行排序。列表将首先按数字(成员编号)排序,然后按字母顺序使用成员编号。struct条目{
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);
}
};
int-num;
字符字母;
friend auto make__tie(入口施工与维护){
返回std::tie(e.num,e.letter);
}
friend bool Operator你是对的,如果你首先对次键进行排序,然后在一个稳定的排序算法中使用主排序键,它应该会给你期望的结果:)你的意思是当我们有两个字母顺序相同的元素时,计数最少的元素应该更小吗?与你刚才说的相反。如果你有两个相同计数的键,我想先显示字母顺序第一的那个。@Slizzered他是对的,但仍然不是这样做的方法。所有这些都可以在一次排序中完成。下面最好的答案是一种更好的方法。谢谢大家!谢谢。这比两次排序更有效!看一看下面的例子我不想用std::tuplet实现字典排序这正是我要做的,upvote!不知道为什么你想要一个额外的make____________________________________________________。它也可以通过这种方式在==
和交换
和其他方法中重用。