deque (double-ended queue) is a container in the C++ Standard Template Library (STL). It enables efficient insertion and deletion of elements at both ends of the container.
Characteristics:
- Random Access: Similar to
vector,dequeprovides random access to any element, allowing direct access via index with a time complexity of O(1). - Dynamic Size:
dequecan dynamically resize at runtime as needed. - Efficient Insertion and Deletion: The time complexity for insertion and deletion at both ends of
dequeis typically O(1). This is more efficient thanvectorfor operations at the beginning, asvectorrequires shifting elements to maintain contiguous memory.
Implementation:
deque internally consists of multiple fixed-size arrays, with the pointers to these arrays stored in a central controller. This implementation supports fast insertion and deletion at both ends without the need for frequent reallocation of the entire internal array, unlike vector.
Use Cases:
- Scenarios requiring frequent addition or removal of elements at both ends: For example, in task queues or work-stealing algorithms, where tasks are frequently added or removed from both ends.
- Scenarios requiring random access but with more frequent insertion or deletion at the front compared to
vector: Althoughvectoris highly efficient for insertion and deletion at the end, its performance is lower for operations at the front, makingdequea suitable choice.
Example:
cpp#include <iostream> #include <deque> int main() { std::deque<int> d; // Adding elements to the back d.push_back(10); d.push_back(20); // Adding elements to the front d.push_front(30); d.push_front(40); // Output: 40 30 10 20 for (int num : d) { std::cout << num << " "; } std::cout << "\n"; // Removing front element d.pop_front(); // Output: 30 10 20 // Removing back element d.pop_back(); // Output: 30 10 // Random access std::cout << "Element at index 1: " << d[1] << std::endl; // Output: 10 return 0; }
In this example, adding and removing elements at both ends of deque is straightforward and efficient. It also demonstrates random access capabilities, highlighting deque's flexibility and efficiency as a valuable data structure for specific scenarios.
2024年7月9日 13:39 回复