In this article we will discuss different techniques to get an element from vector by index or position.

In vector elements are indexed from 0 to size() – 1. To access any element in vector by index vector provides two member functions i.e.

  • at()
  • operator[]

Let’s discuss them in detail,

Access an element in vector using operator []

std::vector provides [] operator i.e.

It returns the reference of element in vector at index n.

Suppose we have a vector of int i.e.

Let’s access element at index 3 using operator [] i.e.

Access and update element in vector using []

As, operator [] returns a reference to the element in vector, so we can change the content of vector too using operator [] i.e.

It will update the value of element at index 3. New contents of vector will be,

We can also keep the returned reference in a reference variable and use later to modify the vector i.e.

New contents of vector will be,

Accessing out of index element through operator []

While accessing any element through operator [] we need to make sure that given index is in range i.e. less than the size of vector, otherwise it will result in undefined behaviour and can also crash application.

Therefore we should always check the size before accessing element using operator [] i.e.

Access an element in vector using vector::at()

std::vector provides an another member function at() i.e.

It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.

Let’s access element at index 3 using at() i.e.

As at() returns a reference, so we can modify the value of element too i.e.

Accessing out of range element using at()

vector::at() will throw out_of_range exception in case we try to access the out of range element i.e.


vector::operator[] vs vector::at()

Both operator[] & at() provides random access to elements in vector in O(1) Complexity. But in case of out of range access operator[] causes undefined behaviour, whereas at() returns proper out_of_range exception. So, at() is more safe to use as compared to operator[].

Complete example is as follows,


To compile the above code use following command,

g++ –std=c++11 example.cpp




Click Here to Subscribe for more Articles / Tutorials like this.