jeudi 25 avril 2019

Trying to do heapsort but got stuck

a new user at coding, trying to do heap sort but got stuck. the error I am getting is:

`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"

Please help!!I guess there is some error in the declaration of class. I am a complete noobie and this is my first course on data structures. It would be great if someone could help.I followed the heapsort code which is in cormen for most of it but the error seems to be prevalent.

#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();
}

Aucun commentaire:

Enregistrer un commentaire