dimanche 14 mars 2021

How to pass Comparator to user define Templeted class?

I want to create a generalized heap data structure, and facing an issue with passing template comparator.

template<typename T, typename C = less<T> > class Heap{
    vector<T> *heap;
    public:
    Heap(vector<T> *arr){
        heap = new vector<T> (arr->begin(), arr->end());
        build_heap();
    }
    void build_heap(){
        size_t n = heap->size();
        for (size_t i=(n-1)/2; i>=0; i--){
            shiftDown(i);
        }
    }
     
    void shiftDown(size_t i){   ///  heap logic
        while(i < heap->size()){
            size_t child = 2*i+1;
            // int min_ind = 2*i+1;
            if(child >= heap->size())
                return;
            if(child+1 < heap->size()){
                if( C(heap->at(child+1),heap->at(child)) ){    //   <----- using C as comparator
                    child++;
                }
            }
            if( C(heap->at(child), heap->at(i)) ){            //   <----- using C as comparator
                swap(heap->at(child), heap->at(i));
                i = child;
            }
            else
                break;
        }
    }
};
int main(){
    vector<int> v={8,7,6,5,4,3,2,1};
    Heap<int, less<int> > heap(&v);
}

error

heap.cpp: In instantiation of ‘void Heap<T, C>::shiftDown(size_t) [with T = int; C = std::less<int>; size_t = long unsigned int]’:
heap.cpp:15:4:   required from ‘void Heap<T, C>::build_heap() [with T = int; C = std::less<int>]’
heap.cpp:10:3:   required from ‘Heap<T, C>::Heap(std::vector<_Tp>*) [with T = int; C = std::less<int>]’
heap.cpp:49:34:   required from here
heap.cpp:32:9: error: no matching function for call to ‘std::less<int>::less(__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&, __gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&)’
   32 |     if( C(heap->at(child+1),heap->at(child)) ){
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...

detailed error

i'm following same syntex of declaration as stl c++ do, still i'm getting error. please help me out.

enter image description here

template<typename T, typename C = less<T> > class Heap;

any help or pointer to help is appreciated. thank you.

Aucun commentaire:

Enregistrer un commentaire