In the C++ Standard Template Library (STL), the most suitable container for implementing FIFO (First-In-First-Out) operations is std::queue. std::queue provides element management based on the FIFO principle, where the earliest added elements are removed first. Internally, it typically uses std::deque (double-ended queue) to store elements, but it can be configured to use std::list or other container types.
Using std::queue
std::queue provides the following basic operations:
push(): Adds an element to the end of the queue.pop(): Removes the first element from the queue.front(): Accesses the first element of the queue.back(): Accesses the last element of the queue.empty(): Checks if the queue is empty.size(): Returns the number of elements in the queue.
Example
Consider managing a customer waiting queue in a banking application; you can use std::queue as follows:
cpp#include <iostream> #include <queue> int main() { std::queue<int> bankQueue; // Add customers to the queue (using IDs) bankQueue.push(101); // Customer 101 enters the queue bankQueue.push(102); // Customer 102 enters the queue bankQueue.push(103); // Customer 103 enters the queue // Display the ID of the customer at the front of the queue std::cout << "First customer ID: " << bankQueue.front() << std::endl; // Customer completes processing and leaves the queue bankQueue.pop(); // Display the ID of the new front customer std::cout << "New first customer ID: " << bankQueue.front() << std::endl; return 0; }
In this example, customer 101 is processed first and leaves the queue, and the front of the queue becomes customer 102. This demonstrates the FIFO behavior effectively.
Conclusion
Therefore, for scenarios requiring FIFO behavior, std::queue is an excellent choice. Its interface is simple and direct, making it ideal for handling queue-like problems. If you have special needs (such as frequent insertion and deletion at both ends), you might consider using std::deque.