优先级队列的理解

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); } } };

2 min

快捷键

vscode 复制当前行到下一行/上一行 shift + alt + 上键/下键 在 Qt Creator 中,在 .h 文件中声明方法后,自动生成 .cpp 定义并跳转的快捷键是 Alt + Enter F4:在 .h 文件和对应的 .cpp 文件之间进行切换。 Shift + F2:在函数的声明和定义之间快速跳转。 Ctrl + /:注释或取消注释选定内容。 Ctrl + i:自动缩进代码 F1 : 跳转QT说明文档

1 min