public member function
<vector>

std::vector::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 vector container.

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

Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.

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 vector.

If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference.

Member types reference and const_reference are the reference types to the elements of the container (see vector 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
// vector::operator[]
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (10);   // 10 zero-initialized elements

  std::vector<int>::size_type sz = myvector.size();

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

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

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

  return 0;
}


Output:
myvector 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).
The reference returned can be used to access or modify elements. Concurrently accessing or modifying different 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.

See also