【发布时间】:2022-01-18 00:01:56
【问题描述】:
我试图弄清楚提升优先级队列是如何实现的,但我很困惑。
头文件(main.hpp):
#ifndef MAIN_HPP
#define MAIN_HPP
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <boost/heap/priority_queue.hpp>
typedef std::int32_t int32_t;
typedef struct st {
int32_t num;
int32_t f;
st() {
std::cout << "DEFAULT" << std::endl;
this->f = 0;
}
st(int32_t num) {
std::cout << "creation\t" << num << std::endl;
this->num = num;
this->f = 0;
}
~st() {
std::cout << "del\t" << num << std::endl;
f = 1;
}
} st;
typedef struct st_c0 {
bool operator()(const st& st0, const st& st1) const {
return (st0.num > st1.num);
}
} st_c0;
typedef struct st_c1 {
bool operator()(const st* st0, const st* st1) const {
return (st0->num > st1->num);
}
} st_c1;
#endif
#include "main.hpp"
int main() {
boost::heap::priority_queue<st, boost::heap::compare<st_c0>> q0;
boost::heap::priority_queue<st*, boost::heap::compare<st_c1>> q1;
st y = st(5);
q0.push(st(44));
q0.push(y);
q0.empty();
std::cout << y.f << std::endl;
return 0;
}
我得到的输出是:
creation 5
creation 44
del 44
del 44
del 44
del 44
del 44
del 5
del 5
del 5
0
del 5
del 5
del 44
对象创建和删除的顺序没有意义。优先级队列的内部是如何工作的,它们的最佳实践是什么(存储指针与存储对象)?
【问题讨论】:
标签: c++ memory boost priority-queue heap