c++11 - 如何将比较器传递给用户定义的模板类?
问题描述
我想创建一个通用的堆数据结构,并面临传递模板比较器的问题。
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;
任何帮助或帮助指针表示赞赏。谢谢你。
解决方案
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);
推荐阅读
- python - ValueError:ValueError:Python 中以 10 为底的 int() 的无效文字
- c++ - 放大/缩小图像 - QT c++
- java - 过滤掉文本文件
- rust - Rust 中的所有输入都应该是可变的吗?
- python - 熊猫将具有匹配子字符串的行返回到字符串
- javascript - 如何在 GraphQL 中为 Input 类型添加自定义指令
- android-room - 如何在 ROOM 库中使用类型转换器来处理复杂数据类型?
- sql - 如何创建一个触发器来检查一个值何时更新定义值仍然为空,如果没有更新表
- python - 如何在 python 上从网站解析特定的 HTML 表
- python - 循环数据的运行平均值:平均偏差和标准偏差?