C++ 代码的输出不是预期的
我试图使用heapsort对hashtable类的对象进行排序C++ 代码的输出不是预期的,c++,recursion,vector,hashmap,heapsort,C++,Recursion,Vector,Hashmap,Heapsort,我试图使用heapsort对hashtable类的对象进行排序 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
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;
}
struct hashmap{
int键;
int值;};
向量堆;
int n;
无效heapify(int i)
{
int l,r,max=i;
l=2*i+1;
r=2*i+2;
如果((heap[r].key>heap[max].key)| |((heap[r].key=heap[max].key)&&(heap[r].value>heap[max].value)))
{
max=r;
}
else如果((heap[l].key>heap[max].key)| |((heap[l].key=heap[max].key)&&(heap[l].value>heap[max].value)))
{
最大值=l;
}
如果(最大!=i)
{
交换(堆[max],堆[i]);
heapify(max);
}
}
void heapsort()
{
对于(int i=n/2-1;i>=0;i--)
希皮菲(i);
而(n>0)
{
交换(堆[n-1],堆[0]);
--n;
heapify(0);
}
}
int main()
{
coutn;
Det(n);
希普索尔();
显示();
返回0;
}
如果我的输入是(1,3)(2,5)(1,2),我的预期输出应该是(1,2)(1,3)(2,5),但这不是我得到的。我得到一些随机数作为输出
假设您希望按键排序,然后按值排序,您也可以与比较函数一起使用:
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;
}
struct hashmap{
int键;
int值;
};
布尔公司(常量哈希映射和a、常量哈希映射和b){
返回tie(a键,a值) cout我认为您不需要heapsort函数中的while循环。像下面这样调用它就足够了:
void heapsort()
{
for (int i=n/2-1;i>=0;i--)
heapify(i);
}
你能添加一个main
函数来重现你的问题吗?注意=
和=
之间的区别。你的变量n
被初始化了,但是你没有给它任何值,这意味着它有一个随机值。然后你在堆中对它进行所有的循环。这听起来有点奇怪去me@DrosvarG默认情况下,全局变量是0
初始化的。这正是问题所在。heapsort
对n==0
不起任何作用。此赋值是否在if
中?(heap[r].key=heap[max].key)
是否将所有函数声明为带有lambda的函数
变量?函数comp=[](const hashmap&a,const hashmap&b)
似乎比bool comp(const hashmap&a,const hashmap&b)的工作量更大
而且可读性也较差。@R0m1但是使用std::sort可以吗?或者不使用std::sort是否有可能防止错误?@Bad\u Panda个人来说,我宁愿使用std::sort,而不是我自己编写的任何排序算法,原因很简单,编写一个好的排序算法可能会非常棘手y、 除非我遗漏了什么,否则我看不出有什么理由不使用它。