In Swift, you can implement a generic deque (double-ended queue) that allows you to efficiently add and remove elements from both ends of the collection. This data structure is useful when you need fast access and manipulation of elements at both ends.
class Deque {
private var items: [Element] = []
var count: Int {
return items.count
}
var isEmpty: Bool {
return items.isEmpty
}
func pushFront(_ element: Element) {
items.insert(element, at: 0)
}
func pushBack(_ element: Element) {
items.append(element)
}
func popFront() -> Element? {
return isEmpty ? nil : items.removeFirst()
}
func popBack() -> Element? {
return isEmpty ? nil : items.removeLast()
}
func peekFront() -> Element? {
return items.first
}
func peekBack() -> Element? {
return items.last
}
}
// Example Usage:
let deque = Deque()
deque.pushBack(1)
deque.pushBack(2)
deque.pushFront(0)
print(deque.popFront()!) // Outputs: 0
print(deque.popBack()!) // Outputs: 2
print(deque.peekFront()!) // Outputs: 1
print(deque.peekBack()!) // Outputs: 1
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?