简体   繁体   中英

How to use template function as comparator in STL algorithm ex: make_heap

#include<iostream>
#include<algorithm>
using namespace std;

template <typename T>
bool HeapComparator (T,T);

template <typename T>
void PrintArray(T arr,int size)
{
    for(int i=0;i<size;i++)
  {
    cout<<arr[i]<<" ";
}
cout<<endl;
}

int main()
{
int arr[7]={1,4,2,5,7,6,3};
int size=7;
PrintArray(arr,size);

cout<<"Max Heap:"<<endl;
make_heap(arr,arr+size); //creates MAX Heap, as no comparator provided.
PrintArray(arr,size);

cout<<"Min Heap:"<<endl;
make_heap(arr,arr+size,HeapComparator); //compilation error here.
PrintArray(arr,size);

return 0;
}   

template <typename T>
bool HeapComparator(T a, T b)
{
if(a>b)
    return false;
else
    return true;
}

It doesn't work. How to use template function as comparator?

您需要实例化模板函数:

make_heap(arr,arr+size,HeapComparator<int>);

You need to pass the template argument when you instantiate the template. Also consider making the arguments of the comparator const refs:

NOTE: I have also included several other improvements to your code - for instance I have simplified the HashComparator.

NOTE2: in this particular case you could have used std::greater<int> as comparator instead of your custom comparator.

#include<iostream>
#include<algorithm>
using namespace std;

template <typename T>
bool HeapComparator (const T&,const T&);

template <typename T>
void PrintArray(T arr,int size)
{
    for(int i=0;i<size;i++) {
      cout<<arr[i]<<" ";
    }
    cout<<endl;
}

int main()
{
  int arr[7]={1,4,2,5,7,6,3};
  int size=7;
  PrintArray(arr,size);

  cout<<"Max Heap:"<<endl;
  make_heap(arr,arr+size); //creates MAX Heap, as no comparator provided.
  PrintArray(arr,size);

  cout<<"Min Heap:"<<endl;
  make_heap(arr,arr+size,HeapComparator<int>); 
  PrintArray(arr,size);

  return 0;
}   

template <typename T>
bool HeapComparator(const T& a,const T& b) {
  return a>b;
}

The easiest way is to encapsulate it in a class.

struct HeapComparator {
    template <typename T>
    bool operator () (T,T);
};

make_heap(arr,arr+size,HeapComparator()); 

template <typename T>
bool HeapComparator::operator () (T a, T b)
{
if(a>b)
    return false;
else
    return true;
}

C++14 generic lambdas will generate the boilerplate automatically:

make_heap(arr,arr+size,[]( auto a, auto b ) { return …; } ); 

Note that your comparator computes !(a>b) or a <= b which is not a valid strict weak ordering. Turning it into a valid condition would yield a<b which is the default.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM