首页 > 解决方案 > 如何将比较器传递给用户定义的模板类?

问题描述

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

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)) ){
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...

详细错误

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

在此处输入图像描述

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

任何帮助或帮助指针表示赞赏。谢谢你。

标签: c++11templatesmetaprogrammingheap-memorycomparator

解决方案


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 传递给模板类,当我们需要比较对象时,我们创建一个函数对象并使用 args 调用 operator() 进行比较。有问题的是,该对象是less<int>

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

推荐阅读