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>
or greater<T>
to the binary_function
type, the operator()
they define is gone.
From my favorite reference :
binary_function does not define operator(); it is expected that derived classes will define this. binary_function provides only three types - first_argument_type, second_argument_type and result_type - defined by the template parameters.
You should pass less<T>
or greater<T>
in directly. You can also use pointer_to_binary_function
, but they've both been deprecated in C++11 in favor of function
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.