【问题标题】:Sorting a Queue of Structs对结构队列进行排序
【发布时间】:2026-01-04 14:45:01
【问题描述】:

我目前有一个队列,其中包含用户指定数量的结构,称为 Process。进程由 pid、burst 和到达组成。我想按到达对队列进行排序,但我不知道从哪里开始。这里有一些伪代码来帮助说明我想说的:

struct Process{
    int pid;
    int burst;
    int arrival;
};

void function(int numProcesses){
    queue<Process> readyQueue;

    // The following loop is a shortened version of my code
    for(int i=0; i<numProcesses;i++){
        readyQueue.push(aProcess);
    }

    // This is where I need help!
    // sort(readyQueue);
}

如果有人可以为我指明正确的方向,我将不胜感激。谢谢!

【问题讨论】:

    标签: c++ sorting queue


    【解决方案1】:

    大多数情况下,您需要为您的班级定义operator&lt;

    struct Process{
        int pid;
        int burst;
        int arrival;
    
        bool operator<(Process const &other) { return arrival < other.arrival; }
    };
    

    完成此操作后,std::sort 将正常工作:

    std::sort(std::begin(readyQueue), std::end(readyQueue));
    

    【讨论】:

    • 这正是我一直在寻找的!我对标准数组以外的任何东西都很陌生。你能解释一下我怎么称呼排序吗?非常感谢。
    • @Rick_Sch:我已经包含了对std::sort 的示例调用。小点:根据您使用的编译器的年龄,您可能需要使用readyQueue.begin() 而不是std::begin(readyQueue)(同样适用于end)。
    • 最后一件事(我希望):当我尝试执行 readyQueue.begin() 方法时出现此错误:error: ‘class std::queue&lt;Process, std::deque&lt;Process, std::allocator&lt;Process&gt; &gt; &gt;’ has no member named ‘begin’ 但如果我尝试 begin(readyQueue),我也会收到此错误方法:‘begin’ was not declared in this scope
    • 您不能遍历队列。您可以推送和弹出,但不能通过队列进行迭代。
    • 抱歉——没有注意到您使用的是实际队列。最简单的方法是使用std::deque。您可能不关心两端的插入和删除,但关心它提供对内容的随机访问。
    【解决方案2】:

    您可以使用标准库 std::sort 从 '' 标头进行排序。您可以提供一个比较器或定义一个较少的运算符。

    struct Process{
        int pid;
        int burst;
        int arrival;
    };
    
        bool operator<(const Process& a, const Process& b) {
              return a.arrival < b.arrival;
        }
    
        void function(int numProcesses){
            std::dequeue<Process> readyQueue;
    
            // The following loop is a shortened version of my code
            for(int i=0; i<numProcesses;i++){
                 readyQueue.push_back(aProcess);
             }
            std::sort(readyQueue.begin(), readyQueue.end());       
        }
    

    http://en.cppreference.com/w/cpp/algorithm/sort

    【讨论】:

    • 他想要按到达排序的流程
    【解决方案3】:

    你应该改用std::priority_queue...否则每次你往队列里推东西时你都必须对队列进行排序。

    注意,你仍然需要定义operator&lt;

    【讨论】:

    • 我曾想过这样做,但这个队列只会被添加一次,所以似乎不需要优先级队列。
    • 请参阅this question,了解这些解决方案在速度方面的优点。
    【解决方案4】:

    您想实现一个日历队列。不要为此使用queue 数据结构,而是使用set

    struct Process{
        int pid;
        int burst;
        int arrival;
        bool operator<(Process const& other) const {
          if (arrival == other.arrival) {
            if (pid == other.pid)
              return this < &other;
            return pid < other.pid;
          }
          return arrival < other.arrival;
        }
    };
    
    void func() {
      std::set<Process> myQueue;
    }
    

    无需显式排序,该集合将始终保持内容排序,您始终可以通过eraseing begin() 迭代器删除第一个。

    【讨论】:

      最近更新 更多