根据此条件对队列进行排序
Sorting a queue based on this criteria
我有一个队列,用于存储指向 Node 对象的指针,这些对象定义为:
class Node {
public:
Node(int, char, Node*);
void setC(char);
char getC();
private:
int x;
char c;
Node* next;
};
在这里,c
可以是"S"、"M"或"L"。(小、中或大)。现在,我想按大小的升序对这个队列进行排序,就像开头/前面的所有"S"节点一样,然后是最后的所有"M"节点和所有"L"节点。
效率并不是一个真正的标准。我该怎么做?
您可以使用
priority_queue
:
#include <queue>
#include <iostream>
using namespace std;
class Node { /* ... */ };
// 'S' < 'M' < 'L'
bool operator< (const Node& lhs, const Node& rhs)
{
switch(lhs.c) {
case 'S': return !('S' == rhs.getC());
case 'M': return ('L' == rhs.getC());
case 'L': return false;
default: throw "must be S, M or L";
}
}
int main() {
priority_queue<Node> pq;
pq.push(Node('S'));
pq.push(Node('M'));
pq.push(Node('L'));
pq.push(Node('S'));
pq.push(Node('M'));
pq.push(Node('L'));
while(pq.size()) {
cout << pq.top().getC() << endl;
pq.pop();
}
}
将按降序给出它们:
L
L
M
M
S
S
您可以创建三个堆栈,然后清空队列并将每种类型放在其中一个堆栈中。然后再次填充队列,从堆栈"S"开始,然后堆栈"M"和最后一个"L"。
这是没有效率的,也许将整个队列存储在一个数组中,然后对其进行排序并在队列中替换是一种更好的方法。
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 更改运行时优先级队列的排序功能
- 内存排序在提升::无锁:队列
- 优先级队列未正确排序
- 排序函数和优先级队列 C++ 中的比较器
- 如何检查队列是否使用 STL 排序
- 对字符串队列进行排序
- C++ 中优先级队列的结构排序条件
- 队列快速排序不排序和打印随机字符串[C ]
- 相同的比较功能为C++中的排序和优先级队列提供不同的输出
- 有效地添加到排序的队列中
- 排序结构的队列
- 我如何在队列中排序元素
- 根据此条件对队列进行排序
- 将添加到队列的第一个元素作为 null 进行排序
- 推送到排序队列实现
- 对队列进行排序 - C/C++
- 命令模式队列按时间排序
- 数据结构-排序队列链表c++