I’m trying to write a function that will print the contents of both minheap and maxheap but I’m having trouble with the comparators. I tried using a ternary operator, but it doesn’t work since std::less and std::greater are different types. What is wrong with how I am trying to use the comparators?
#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;
}
Link error:
/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&)’
edit:
I’ve also tried using a binary_function pointer and allocating on the heap, and now i get a different error:
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;
}
error:
/usr/include/c++/4.6/bits/stl_heap.h:305:4: error: ‘__comp’ cannot be used as a function
You are the victim of object slicing.
When you assign
less<T>orgreater<T>to thebinary_functiontype, theoperator()they define is gone.From my favorite reference:
You should pass
less<T>orgreater<T>in directly. You can also usepointer_to_binary_function, but they’ve both been deprecated in C++11 in favor offunction.