C++ Standard Library C++ STL Library

C++ <vector> - operator[] Function



The C++ vector::operator[] function returns a reference to the element of the vector at the specified position. If the specified position is not within the bounds of valid elements in the vector, the function does not throw any exception.

Note: The vector::operator[] function produces the same result as vector::at function, except vector::at do check the specified position against bounds of valid elements in the vector.

Syntax

reference operator[] (size_type n);
const_reference operator[] (size_type n) const;
reference operator[] (size_type n);
const_reference operator[] (size_type n) const;

Parameters

n Specify position of the element in the vector.

Return Value

The element at the specified position in the vector.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, vector::operator[] function returns a reference to the element of the vector at the specified position.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector (5);

  for(int i=0; i<MyVector.size(); i++)
    MyVector[i] = 100*(i+1);

  cout<<"MyVector contains: ";
  for(int i=0; i<MyVector.size(); i++)
    cout<<MyVector[i]<<" ";

  return 0;
}

The output of the above code will be:

MyVector contains: 100 200 300 400 500

❮ C++ <vector> Library