public member function
<deque>

std::deque::operator[]

      reference operator[] (size_type n);const_reference operator[] (size_type n) const;
Access element
Returns a reference to the element at position n in the deque container.

A similar member function, deque::at, has the same behavior as this operator function, except that deque::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.

Parameters

n
Position of an element in the container.
Notice that the first element has a position of 0 (not 1).
Member type size_type is an unsigned integral type.

Return value

The element at the specified position in the container.

Member types reference and const_reference are the reference types to the elements of the container (see deque member types).

Example

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
// deque::operator[] example: reversing order
#include <iostream>
#include <deque>

int main ()
{
  std::deque<int> mydeque (10);   // 10 zero-initialized elements
  std::deque<int>::size_type sz = mydeque.size();

  // assign some values:
  for (unsigned i=0; i<sz; i++) mydeque[i]=i;

  // reverse order of elements using operator[]:
  for (unsigned i=0; i<sz/2; i++)
  {
    int temp;
    temp = mydeque[sz-1-i];
    mydeque[sz-1-i]=mydeque[i];
    mydeque[i]=temp;
  }

  // print content:
  std::cout << "mydeque contains:";
  for (unsigned i=0; i<sz; i++)
    std::cout << ' ' << mydeque[i];
  std::cout << '\n';

  return 0;
}

Output:
mydeque contains: 9 8 7 6 5 4 3 2 1 0


Complexity

Constant.

Iterator validity

No changes.

Data races

The container is accessed (neither the const nor the non-const versions modify the container).
Element n is potentially accessed or modified. Concurrently accessing or modifying other elements is safe.

Exception safety

If the container size is greater than n, the function never throws exceptions (no-throw guarantee).
Otherwise, the behavior is undefined (which may include throwing).

See also