gpt4 book ai didi

c++ - 模板类中的比较器

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:01:12 25 4
gpt4 key购买 nike

我正在研究堆实现。它必须是模板类,我需要它有自己的比较器,传入构造函数。我该怎么做?

我已经试过了:

template <typename T>
class Heap{
public:
Heap(int size, bool (*comparator) (const T & a, const T & b) = [] (const T & a, const T & b){
return a < b;
})

// other unimportant methods
}

适用于:

Heap<int> heap(4);

还有:

Heap<int> heap(4, [](const int & a, const int & b){ return false; })

但是当我尝试将它与这样的指针一起使用时(其中 offer 是某种结构):

Heap<Offer*> heap2(3, [](Offer const * a, Offer const * b){
return false;
});

我遇到了这个编译错误:

test.cpp: In function ‘int main()’:
test.cpp:126:3: error: invalid user-defined conversion from ‘main()::<lambda(const Offer*, const Offer*)>’ to ‘bool (*)(Offer* const&, Offer* const&)’ [-fpermissive]
});
^
test.cpp:124:59: note: candidate is: main()::<lambda(const Offer*, const Offer*)>::operator bool (*)(const Offer*, const Offer*)() const <near match>
Heap<Offer*> heap2(3, [](Offer const * a, Offer const * b){
^
test.cpp:124:59: note: no known conversion from ‘bool (*)(const Offer*, const Offer*)’ to ‘bool (*)(Offer* const&, Offer* const&)’
test.cpp:13:5: note: initializing argument 2 of ‘Heap<T>::Heap(int, bool (*)(const T&, const T&)) [with T = Offer*]’
Heap(int size, bool (*comparator) (const T & a, const T & b) = [] (const T & a, const T & b){

如何让它适用于这两种情况?

最佳答案

对于指针版本:'T' 是一个指针,然后需要作为 const ref 传递 - 它不是它指向的数据,在这里要被 const 限定,而是指针 ref 本身。

template <typename T>
class Heap{
public:
Heap(int size, bool (*comparator) (const T & a, const T & b)
= [] (const T & a, const T & b){
return a < b;
}) {};

// other unimportant methods
};


int main()
{
Heap<int*> heap2(3, [](int* const& a, int* const& b){
return false;
});

// analogous to
Heap<int> heap(4, [](const int & a, const int & b){
return false;
});
// but it's the pointer to the datum in the first,
// and the datum itself in the latter case
}

live at Coliru

关于c++ - 模板类中的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33564191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com