c++ - 代码的输出未按预期进行
问题描述
我正在尝试使用 heapsort 对类哈希表的对象进行排序
struct hashmap{
int key;
int value; };
vector<hashmap> heap;
int n;
void heapify(int i)
{
int l,r,max=i;
l=2*i+1;
r=2*i+2;
if((heap[r].key>heap[max].key)||((heap[r].key=heap[max].key)&&(heap[r].value>heap[max].value)))
{
max=r;
}
else if((heap[l].key>heap[max].key)||((heap[l].key=heap[max].key)&&(heap[l].value>heap[max].value)))
{
max=l;
}
if(max!=i)
{
swap(heap[max],heap[i]);
heapify(max);
}
}
void heapsort()
{
for (int i=n/2-1;i>=0;i--)
heapify(i);
while(n>0)
{
swap(heap[n-1],heap[0]);
--n;
heapify(0);
}
}
int main()
{
cout<<"Enter the no of elements : ";
cin>>n;
Det(n);
heapsort();
display();
return 0;
}
如果我的输入是 (1,3) (2,5) (1,2) 我的预期输出应该是 (1,2) (1,3) (2,5) 但这不是我得到的。我得到一些随机数作为输出。
解决方案
假设您想先按键排序,然后按值排序,您也可以将std::sort与比较函数一起使用:
struct hashmap{
int key;
int value;
};
bool comp(const hashmap& a, const hashmap& b) {
return tie(a.key, a.value) < tie(b.key, b.value);
}
int main()
{
vector<hashmap> v{
{1, 3}
, {2, 5}
, {1, 2}
};
sort(v.begin(), v.end(), comp);
for (const auto& h : v) {
cout << '(' << h.key << ',' << h.value << ')';
}
cout << endl;
return 0;
}
推荐阅读
- html - 不带标签的样式单选输入
- javascript - JS中的重置功能不断重新加载页面
- sql - 请解释此查询如何与 "WHERE and AND" 一起使用。提前致谢
- c - 如何配置 GCC 以自动包含头文件?
- linux - 如何避免内核线程和定时器对进程的影响?
- fonts - 检测阿拉伯字体
- laravel - 我在关系中使用 select 语句时遇到问题,如何在此语句中选择 images.path 列
- counter - 在 eBPF 中强制跟踪连接的最大阈值
- javascript - 如何将字符串 React 中的查询词斜体化
- javascript - 当我在 Jest 中导入我的组件时,所有测试都失败了