C++ 优先队列(priority_queue) 和 比较函数

优先级(priority):谁更先被取出
堆类型(max/min heap):堆顶元素是最大(大顶堆)还是最小(小顶堆)



比较函数bool compare(T a, T b) 返回true
STL 默认 comparator 表示 “a 是否小于 b”,
#include <queue>
struct Order
{
    double price;
    int volume;
    long long timestamp;    // 用于同价的先进先出

    // 买单队列的比较函数: 价格高的排在前面,大顶堆
    struct BuyComp {
        bool operator() (const Order& a, const Order& b) {
            if(a.price != b.price) return a.price < b.price;
            return a.timestamp > b.timestamp;
        }
    };
    // 卖单队列的比较函数: 价格低的排在前面,小顶堆
    struct SellComp {
        bool operator() (const Order& a, const Order& b) {
            if(a.price != b.price) return a.price > b.price;
            return a.timestamp > b.timestamp;
        }
    };
};

class MatchingEngine {
    priority_queue<Order, vector<Order>, Order::BuyComp> buyOrders;
    priority_queue<Order, vector<Order>, Order::SellComp> sellOrders;
    long long timer = 0;

public:
    void process(string type, double price, int volume) {
        Order current = {price, volume, timer++};

        if (type == "BUY") { // 尝试与现有的卖单撮合
            while(!sellOrders.empty() && current.volume > 0 
                    && current.price >= sellOrders.top().price) {
                Order bestSell = sellOrders.top();
                sellOrders.pop();
                
                int tradeVol = min(bestSell.volume, current.volume);
                cout << "成交: price:" << bestSell.price << "volume: " << tradeVol << endl;
                current.volume -= tradeVol;
                bestSell.volume -= tradeVol;
                
                if(bestSell.volume > 0) sellOrders.push(bestSell);
            }
            if(current.volume > 0) buyOrders.push(current);
        }
        else if (type == "SELL") { // 尝试与现有的买单撮合
            while(!buyOrders.empty() && current.volume > 0
                        && current.price < buyOrders.top().price) {
                Order bestBuy = buyOrders.top();
                buyOrders.pop();
                
                int tradeVol = min(bestBuy.volume, current.volume);
                cout << "成交: price:" << current.price << "volume: " << tradeVol << endl;
                current.volume -= tradeVol;
                bestBuy.volume -= tradeVol;
                
                if(bestBuy.volume > 0) buyOrders.push(bestBuy);
            }
            if(current.volume > 0) sellOrders.push(current);
        }
    }
};