I'm trying to build a home-made min-heap with template class so I can work on Dijkstra or Prim. However the find_min() function does not work with std::min_element(). Any clue will be greatly appreciated. Thanks!
the error message from VC2010express, in short, says
error C2780: '_FwdIt std::min_element(_FwdIt,_FwdIt)' : expects 2 arguments - 3 provided
and the code below:
#ifndef MIN_HEAP_H
#define MIN_HEAP_H//use (unsorted) vector and min() algorithm
#include <vector>
#include 开发者_StackOverflow<algorithm>
#include <functional>
template <typename T>
class MinHeap{
std::vector<T> c;//container
typedef typename std::vector<T>::iterator iterator;
bool compare_node(const T& lhs,const T& rhs) const {return lhs<rhs;}//define compare function for nodes
public:
MinHeap():c(){}//default constructor
inline void insert(T node){c.push_back(node);}
iterator find_min(){
iterator min_node=std::min_element(c.begin(),c.end(),compare_node);//doesn't build
return min_node;
}
// deleteMin();
// deleteNode(node);
// decreaseKey(node);
};
#endif
std::min_element
's 3rd argument is either a functor object, or a function pointer to a comparator. The comparator function must be a free function; you're trying to give it a non-static
member function.
As there is no reason for compare_node
to be a member function, you may as well make it a free function instead.
Having said that, your compare_node
is equivalent to the implementation of the default comparator for std::min_element
, so you may as well not use it at all.
As mentioned already you can leave out the comparator argument and just call std::min_element(c.begin(), c.end());
.
Another option would be to use a std::set
instead of a vector. A set keeps its elements ordered, so you can get the smallest element by calling *theSet.begin();
.
精彩评论