【发布时间】:2019-10-02 12:43:43
【问题描述】:
我有以下代码:
#include <iostream>
#include <map>
#include <list>
#include <queue>
#include <memory>
enum class CommandType : uint8_t {
Comm1,
Comm2,
Comm3,
Comm4,
Comm5
};
enum class Priority {
HIGH,
MEDIUM,
LOW
};
std::map<CommandType, Priority> priorities = {
{ CommandType::Comm1, Priority::LOW },
{ CommandType::Comm2, Priority::LOW },
{ CommandType::Comm3, Priority::LOW },
{ CommandType::Comm4, Priority::LOW },
{ CommandType::Comm5, Priority::LOW }
};
class QueueEntry
{
public:
QueueEntry(CommandType type)
: type_(type) {}
CommandType getType() { return type_; }
private:
CommandType type_;
};
struct QueueEntryPriorityComparator {
bool operator()(std::unique_ptr<QueueEntry>& entry1, std::unique_ptr<QueueEntry>& entry2) const
{
auto p1 = priorities.at(entry1->getType());
auto p2 = priorities.at(entry2->getType());
return p1 < p2;
}
};
std::priority_queue<std::unique_ptr<QueueEntry>, std::deque<std::unique_ptr<QueueEntry>>, QueueEntryPriorityComparator> q;
void print()
{
decltype(q) queueCopy;
queueCopy.swap(q);
while (!queueCopy.empty()) {
auto& top = queueCopy.top();
std::cout << "Command type: " << static_cast<uint32_t>(top->getType()) << std::endl;;
q.emplace(std::make_unique<QueueEntry>(top->getType()));
queueCopy.pop();
}
}
int main()
{
q.emplace(std::make_unique<QueueEntry>(CommandType::Comm1));
q.emplace(std::make_unique<QueueEntry>(CommandType::Comm2));
q.emplace(std::make_unique<QueueEntry>(CommandType::Comm3));
q.emplace(std::make_unique<QueueEntry>(CommandType::Comm4));
q.emplace(std::make_unique<QueueEntry>(CommandType::Comm5));
print();
std::cout << std::endl;
print();
std::cout << std::endl;
print();
return 0;
}
每个元素都有相同的优先级,即Priority::LOW;
问题是,这些元素是如何放在priority_queue 中的?
每当我打印队列时,元素都处于不同的位置。 对我来说重要的是,如果有任何新元素进入priority_queue,则应将其放在具有相同优先级的最后一个元素之后。
使用std::priority_queue可以实现还是必须自己封装?
【问题讨论】:
-
priority_queue 的规范中没有任何内容说明具有相同优先级的元素是如何排序的。您必须添加有关数据的信息并定义新的排序以考虑插入顺序。
-
如果您希望具有相同优先级的新元素具有较低的优先级,它们的优先级并不相同,是吗?
标签: c++ stl queue priority-queue