我在使用比较器初始化set时遇到问题。
.h文件:
class Comparator
{
public:
const std::vector <long long> &dist;
public:
Comparator(const std::vector <long long>& _dist): dist(_dist){}
};
class SetComparator: public Heap
{
private:
std::set <int, Comparator> heap;
public:
SetComparator();
};
这是构造函数:
SetComparator::SetComparator()
{
heap(Comparator(dist));
}
当我尝试编译它时,我有这样的错误:
SetComparator.cpp:8:23: error: no match for call to '(std::set<int, Comparator>) (Comparator)'
heap(Comparator(dist));
我的代码应该更正一些?
答案 0 :(得分:1)
初始化std::set
的自定义比较器的唯一方法是在set的构造函数中指定它。非静态数据成员&#39;构造函数调用可以在 mem-initializer-list 上自定义:
SetComparator::SetComparator() : heap(Comparator(dist)) {}
// ~~~~~~~~~~~~~~~~~~~~~^
或(C ++ 11)提供 member-initializer :
class SetComparator: public Heap
{
private:
std::vector <long long> dist;
std::set <int, Comparator> heap{ Comparator(dist) };
// ~~~~~~~~~~~~~~~^
public:
SetComparator();
};