gpt4 book ai didi

c++ - 尝试进行堆排序但卡住了

转载 作者:行者123 更新时间:2023-11-28 04:19:08 24 4
gpt4 key购买 nike

编码的新用户,尝试进行堆排序但卡住了。我得到的错误是:

`heap.cpp: In member function ‘void heap::Heapsort()’:
heap.cpp: error: no matching function for call to ‘heap::swap(__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&, __gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&)’
swap(A[0],A[i]);
^
In file included from /usr/include/c++/8/vector:64,
from heap.cpp:2:
/usr/include/c++/8/bits/stl_vector.h:1367:7: note: candidate: ‘void std::vector<_Tp, _Alloc>::swap(std::vector<_Tp, _Alloc>&) [with _Tp = int; _Alloc = std::allocator<int>]’
swap(vector& __x) _GLIBCXX_NOEXCEPT
^~~~
/usr/include/c++/8/bits/stl_vector.h:1367:7: note: candidate expects 1 argument, 2 provided"

请帮忙!!我猜类的声明有一些错误。我是一个完全的新手,这是我关于数据结构的第一门类(class)。如果有人能提供帮助,那就太好了。我大部分时间都遵循了 cormen 中的堆排序代码,但错误似乎很普遍。

#include<iostream>
#include<vector>
#include<iomanip>
using namespace std;
class heap:public vector<int>{
private:
vector<int> &A;
int length;
int heap_size;
int P(int i){return (i-1)/2;}
int le(int i){return 2*i+1;}
int ri(int i){return 2*i+2;}
public:
void maxheap(int i);
void bmh(void);
void Heapsort(void);
heap(initializer_list<int> il):
vector<int>(il), A(*this),length(A.size()),heap_size(0) {}
heap(void):A(*this),length(A.size()),heap_size(0) {}// constructor
void show(void);

};
void heap::maxheap(int i)
{
int largest;
int l=le(i),r=ri(i);
if(l<=heap_size-1)&&A[l]>A[i])
largest=l;
else
largest=i;
if(r<=heap_size-1&&A[r]>A[i])
largest=r;
else
largest=i;
if(largest!=i){
swap(A[largest],A[i]);
maxheap(largest);
}
};
void heap::bmh(void)
{
heap_size=length;
for(int i=length/2;i>=0;i--)
{
maxheap(i);
}
}
void heap::Heapsort(void)
{
bmh();
for(int i=length-1;i>0;i--){
swap(A[0],A[i]);
heap_size=heap_size-1;
maxheap(i);
}
}
void heap::show(void)
{
for(int i=0;i<length-1;i++)
{
cout<<A[i]<<" ";
}
cout<<endl;
}
int main()
{
heap h<int>={16,4,10,14,7,9,3,2,8,1};
h.show();
//h.Build_Max_Heap();
//h.show();
// Test the member functions of heap class.
h.Heapsort();
h.show();
}

最佳答案

std::vector<int>有一个名为 swap 的成员.该成员隐藏全局函数std::swap .您可以通过其完全限定名称访问它。

此外,您还没有包含 <algorithm><utility> , 所以有可能 std::swap甚至没有宣布。

关于c++ - 尝试进行堆排序但卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com