模板类中的Min_element()

min_element() within template class

本文关键字:element Min      更新时间:2023-10-16

我试图用模板类构建一个自制的最小堆,这样我就可以在Dijkstra或Prim上工作。然而,find_min()函数不能与std::min_element()一起工作。任何线索将不胜感激。谢谢!

来自VC2010express的错误消息,简而言之,说

错误C2780: '_FwdIt std::min_element(_FwdIt,_FwdIt)':期望2个参数-提供3个

和下面的代码:

#ifndef MIN_HEAP_H
#define MIN_HEAP_H//use (unsorted) vector and min() algorithm
#include <vector>
#include <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的第三个实参要么是一个函子对象,要么是指向比较器的函数指针。比较器函数必须是自由函数;你试图给它一个非static 成员函数

由于没有理由将compare_node作为成员函数,您不妨将其改为自由函数。

话虽如此,您的compare_node相当于std::min_element的默认比较器的实现,因此您可能根本不使用它。

如前所述,您可以省略比较器参数,只调用std::min_element(c.begin(), c.end());

另一种选择是使用std::set而不是vector。set保持其元素有序,因此可以通过调用*theSet.begin();来获取最小的元素。