C++ Access Elements from a Deque

ww‮ditfigi.w‬ea.com

In C++, you can access the elements of a deque using the subscript operator [] or the at() method. Both methods take an index as a parameter and return a reference to the element at that index.

Here's an example of how to access elements from a deque using the subscript operator and the at() method:

#include <iostream>
#include <deque>

int main() {
  std::deque<int> d {1, 2, 3, 4, 5};
  
  // Access elements using the subscript operator
  std::cout << "Element at index 0: " << d[0] << std::endl;
  std::cout << "Element at index 2: " << d[2] << std::endl;
  
  // Access elements using the at() method
  std::cout << "Element at index 3: " << d.at(3) << std::endl;
  std::cout << "Element at index 4: " << d.at(4) << std::endl;
  
  return 0;
}

In this example, we create a deque d with five elements, and then we use the subscript operator and the at() method to access elements at different positions in the deque. We then print the values of these elements using std::cout.

The output of this program is:

Element at index 0: 1
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

As you can see, we have successfully accessed the elements of the deque using the subscript operator and the at() method. It's important to note that the at() method performs bounds checking and throws an std::out_of_range exception if the index is out of range, while the subscript operator does not perform bounds checking and can lead to undefined behavior if the index is out of range.