如何将 Comparator 传递给用户定义的 Templeted class?

How to pass Comparator to user define Templeted class?

我想创建一个通用的堆数据结构,并面临传递 模板比较器 的问题。

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

错误

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

我遵循与 stl c++ 相同的声明语法,但我仍然遇到错误。请帮帮我。

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

感谢任何帮助或指向帮助的指针。谢谢。

template<class T>
class Comparator{
    bool operator()(const T &a, const T &b){
        ...
        // returns logic
    }
}


template<class T, class Comp >
class AnyClass{

public:
    ...
    void function(){
   //   code ...
        Comp<T>()(obj1, obj2);
    }
    ...

}

调用 sytex :

...

AnyClass *obj = new AnyClass<Type , Comparator>();
obj.function()

...

将 Comparator 传递给模板 class 以及何时需要比较对象 我们创建一个功能对象并调用 operator() 与 args 进行比较。 有问题的是,该对象是 less<int>.

Comp<T>()(obj1, obj2);