【发布时间】:2012-10-10 15:39:07
【问题描述】:
我正在尝试编写一个函数来打印 minheap 和 maxheap 的内容,但是比较器遇到了问题。我尝试使用三元运算符,但它不起作用,因为 std::less 和 std::greater 是不同的类型。我尝试使用比较器的方式有什么问题?
#include <functional>
template<typename T> void printheap (T* v, int begin, int end, bool max) {
end--;
std::binary_function<T,T,bool> comp;
if (max) comp = less<T>();
else comp = greater<T>();
while (end>=begin) {
cout << v[begin] << " ";
pop_heap(&v[begin], &v[end+1], comp );
end--;
}
cout << endl;
}
链接错误:
/usr/include/c++/4.6/bits/stl_heap.h:305:4: error: no match for call to ‘(std::binary_function<int, int, bool>) (int&, int&)’
编辑:
我也尝试过使用 binary_function 指针并在堆上分配,现在我得到了一个不同的错误:
template<typename T> inline void printheap (T* v, int begin, int end, bool max) {
...
std::binary_function<T,T,bool> *comp;
if (max) comp = new less<T>();
else comp = new greater<T>();
...
pop_heap(&v[begin], &v[end+1], (*comp) );
...
delete comp;
}
错误:
/usr/include/c++/4.6/bits/stl_heap.h:305:4: error: ‘__comp’ cannot be used as a function
【问题讨论】:
-
也使用
std::function代替binary_function,因为后者在C++11 中已被弃用。这可能会解决您的问题。 -
我确实忘记取消引用,但这样做又会产生第一个编译器错误
标签: c++ algorithm data-structures stl functional-programming