混淆了定义自定义优先级队列和使用C++中的make_heap等方法初始化堆之间的区别
Confused of the difference between defining a custom priority queue and initializing a heap using methods like make_heap in C++
我试图解决一个编码问题,该问题要求我使用堆来按特定顺序获取项。当我试图使用自定义priority_queue和make_heap来实现解决方案时,我发现我们在自己的比较器中传递的方式是不同的,而且令人困惑。
c++.com说:
priority_queue (const Compare& comp = Compare(), const Container& ctnr = Container());
Comp是用于对堆进行排序的比较对象。这可能是一个函数指针或函数对象,能够通过比较其两个参数来执行严格的弱排序。
void make_heap (RandomAccessIterator first, RandomAccessIterator last,
Compare comp );
这里comp是一个二进制函数,它接受范围中的两个元素作为参数,并返回一个可转换为bool的值。它可以是函数指针,也可以是函数对象。
我对这里使用2 comp的区别感到困惑,当我试图实现我的代码时:
// first I define a functor and a static function, both used to be passed as the comp argument;
class isGreater {
public:
isGreater() {}
inline bool operator() (const ListNode* l1, const ListNode* l2) const {
return l1->val >= l2->val;
}
};
static bool isLarger(const ListNode* l1, const ListNode* l2) {
return l1->val >= l2->val;
}
// then I tried several ways to define a custom pq and heap:
// correct
priority_queue<ListNode*, std::vector<ListNode*>, isGreater> p;
// wrong, error: data member instantiated with function type
// 'value_compare'(aka 'isGreater ()')
priority_queue<ListNode*, std::vector<ListNode*>, isGreater()> p;
// wrong, passing a function pointer like this is not allowed
// error: template argument for template type parameter must be a type
priority_queue<ListNode*, std::vector<ListNode*>, isLarger> p;
// correct
make_heap(v.begin(), v.end(), isGreater());
// correct, here passing a function pointer like this is allowed
make_heap(v.begin(), v.end(), isLarger);
// wrong, the "()" is needed, different from how we define priority queue
make_heap(v.begin(), v.end(), isGreater);
我对我们把comp作为论据的不同方式感到困惑。有人能帮我解这些谜题吗?
为了了解发生了什么,您需要了解isGreater
和isGreater()
之间的区别
isGreater
是一个类型的名称。它可以去类型可以去的地方,即进入模板参数(三角括号)和声明isGreater()
是一个构造函数调用,它生成类型为isGreater
的对象。它可以放在表达式可以放的任何地方,例如,它可以用作函数参数
现在错误应该清楚了:不允许使用类型名isGreater
来代替对象表达式isGreater()
,反之亦然。
模板中的比较函数是类型。构造函数或make_heap
函数中的比较函数是一个可调用的对象。
isLarger
函数是一个可调用的对象而不是类型,因此不能将其用作std::priority_queue
的模板参数。
另一方面,类isGreate
是一种类型,可用于创建可调用对象。
相关文章:
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 为什么我的 heap.h 文件给我一个LNK2001错误?
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- make 命令如何避免重新编译未更改的源文件?
- MAKE:找不到包含的用户定义的头文件?
- 'make check' GLIBC 运行时的链接问题
- 当为可变性配置时,boost::heap::d_ary_heap 保留的额外 std::list 的目的是什么?
- 了解 Linux 虚拟内存:valgrind 的 massif 输出显示了有和没有 --pages-as-heap 的主要差异
- Qt5 [make -snap] 无法正确编译:进程"/usr/bin/snap"代码 1 退出
- mingw32-make 使用"MinGW Makefiles"生成器跟踪 CMAKE 无法将可执行文件链接到对象库
- make 命令创建 .file,但不创建应用程序文件
- 如何摆脱导入的 make 项目中的 Eclipse 索引器"Type std::... could not be resolved"错误
- Qt Creator 在执行步骤 "make" 时出现编译错误,-fno-stack-limit
- 如何使用MySQL Connector and Make设置C++项目
- 使用 make 将对象文件放在特定目录中
- 我是 C++ 的新手,我试图调用 make 一个以 2 个类作为其参数的类构造函数
- "Make"失败并出现 Clang 错误 - 如何从 Clang 获得错误?
- 防止 GNU Make 在每次构建时生成 protobuf 代码
- Make zmqpp::socket::connect a std::future
- 链接从命令行转换为Make的库