capypad
0 day streak
rust / intermediate
Snippet

Efficient Queue Operations with VecDeque

VecDeque (double-ended queue) provides O(1) operations for adding and removing from both ends, making it ideal for queue and breadth-first search implementations. Unlike a Vec where push_front is O(n), VecDeque supports efficient prepend operations. The push_back method adds to the rear, push_front adds to the front, and pop_front/pop_back remove from respective ends. This data structure is perfect for task queues, task scheduling, or any scenario where you need FIFO (first-in-first-out) behavior with occasional priority insertions at the front.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::collections::VecDeque;
 
#[derive(Debug, Clone, PartialEq)]
struct Task {
id: u32,
description: String,
priority: u8,
}
 
fn main() {
let mut task_queue: VecDeque<Task> = VecDeque::new();
 
task_queue.push_back(Task {
id: 1,
description: "Design feature".to_string(),
priority: 2,
});
task_queue.push_back(Task {
id: 2,
description: "Write tests".to_string(),
priority: 3,
});
task_queue.push_front(Task {
id: 3,
description: "Fix critical bug".to_string(),
priority: 1,
});
 
println!("Queue order:");
for task in &task_queue {
println!(" {:?}", task);
}
 
if let Some(high_priority) = task_queue.pop_front() {
println!("\nProcessing: {:?}", high_priority);
}
 
if let Some(back_task) = task_queue.pop_back() {
println!("Removed from back: {:?}", back_task);
}
 
let remaining: VecDeque<Task> = task_queue.clone();
println!("\nRemaining {} tasks", remaining.len());
 
task_queue.clear();
println!("Queue cleared, length: {}", task_queue.len());
}
Breakdown
1
use std::collections::VecDeque;
Import VecDeque from collections for efficient double-ended queue operations
2
#[derive(Debug, Clone, PartialEq)]
Derive traits needed for printing, cloning, and comparison of Task struct
3
let mut task_queue: VecDeque<Task> = VecDeque::new();
Create empty VecDeque to hold Task items
4
push_back adds to rear
Task 2 becomes the back element with lowest priority
5
push_front Task { id: 3, ... }
Critical bug task inserted at front with highest priority (1)
6
for task in &task_queue {
Iterate in insertion order showing front to back arrangement
7
if let Some(high_priority) = task_queue.pop_front() {
Remove and process highest priority task from front (O(1) operation)
8
if let Some(back_task) = task_queue.pop_back() {
Remove lowest priority task from back if needed
9
let remaining: VecDeque<Task> = task_queue.clone();
Clone remaining tasks to preserve original before clearing
10
task_queue.clear();
Remove all tasks from queue at once