intermediateCollections
VecDeque
Double-ended queue with efficient push/pop from both ends.
VecDeque
Double-ended queue with efficient push/pop from both ends.
Difficulty
Intermediate
Code
rust
use std::collections::VecDeque;
fn main() {
let mut deque = VecDeque::new();
// push to back
deque.push_back(1);
deque.push_back(2);
deque.push_back(3);
// push to front
deque.push_front(0);
println!("deque: {:?}", deque);
// pop from both ends
println!("pop_front: {:?}", deque.pop_front());
println!("pop_back: {:?}", deque.pop_back());
println!("deque: {:?}", deque);
// use as a sliding window
let mut window = VecDeque::with_capacity(3);
for i in 0..5 {
if window.len() == 3 {
window.pop_front();
}
window.push_back(i);
println!("window: {:?}", window);
}
}Explanation
VecDeque is a double-ended queue with O(1) operations.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the collections category to build a complete understanding of this topic.