給定 4 個佇列物件,需找出當前元素最少者,並對該佇列進行後續操作(如入隊)。關鍵在於**不複製佇列**,而是取得**參考或指標**以操作原物件。
原回答回傳 BankQueue 物件會觸發複製建構,後續操作的是副本而非原佇列。
// 假設佇列型別為 std::queue<Customer> 或自訂類別
using QueueRef = std::queue<Customer>&; // 或 BankQueue&
QueueRef findShortest(std::array<QueueRef, 4> queues) {
auto shortest = queues[0];
for (size_t i = 1; i < queues.size(); ++i) {
if (queues[i].size() < shortest.size()) {
shortest = queues[i];
}
}
return shortest; // 回傳參考,綁定原物件
}
// 使用
auto& q = findShortest(myQueues);
q.push(newCustomer); // 直接操作原佇列
BankQueue* findShortest(BankQueue* qs[4]) {
BankQueue* minQ = qs[0];
for (int i = 1; i < 4; ++i) {
if (qs[i]->size() < minQ->size()) minQ = qs[i];
}
return minQ; // 回傳指標
}
size() 通常為 O(1),無需手動計算 rear - front(僅適用環狀陣列實作)。