Implementing a priority queue in Swift allows you to efficiently manage a collection of elements based on their priority. Below is an example of how you can create a simple priority queue class using a min-heap data structure.
class PriorityQueue {
private var elements: [(priority: Int, value: T)] = []
func push(_ value: T, priority: Int) {
elements.append((priority, value))
elements.sort(by: { $0.priority < $1.priority })
}
func pop() -> T? {
return elements.isEmpty ? nil : elements.removeFirst().value
}
func peek() -> T? {
return elements.first?.value
}
var isEmpty: Bool {
return elements.isEmpty
}
var count: Int {
return elements.count
}
}
// Example usage
let priorityQueue = PriorityQueue()
priorityQueue.push("Low priority task", priority: 5)
priorityQueue.push("High priority task", priority: 1)
priorityQueue.push("Medium priority task", priority: 3)
while !priorityQueue.isEmpty {
print(priorityQueue.pop()!) // Output: High priority task, Medium priority task, Low priority task
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?