根据此条件对队列进行排序

Sorting a queue based on this criteria

本文关键字:排序 队列 条件      更新时间:2023-10-16

我有一个队列,用于存储指向 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"。

这是没有效率的,也许将整个队列存储在一个数组中,然后对其进行排序并在队列中替换是一种更好的方法。