C++ - C++ Deque Part 3: Accessing Elements in a Deque
Deques allow direct access to elements using:
.front(): Returns the first element.
.back(): Returns the last element.
.at(index): Returns the element at a specific index (with bounds checking).
Example 5: Accessing Front and Back Elements
#include <iostream>
#include <deque>
int main() {
std::deque<char> letters = {'A', 'B', 'C', 'D', 'E'};
std::cout << "First: " << letters.front() << std::endl;
std::cout << "Last: " << letters.back() << std::endl;
return 0;
}
Output:
mathematica
First: A
Last: E
Example 6: Using at() for Safe Index Access
#include <iostream>
#include <deque>
int main() {
std::deque<int> dq = {1, 2, 3, 4, 5};
std::cout << "Element at index 2: " << dq.at(2) << std::endl;
return 0;
}
Output:
Element at index 2: 3