C++ Standard Library C++ STL Library

C++ <vector> - front() Function



The C++ vector::front function returns a reference to the first element of the vector. Please note that, Unlike the vector::begin function, which returns the iterator pointing to the first element, it returns the a direct reference to the same element of the vector.

Syntax

reference front();
const_reference front() const;
reference front();
const_reference front() const;

Parameters

No parameter is required.

Return Value

A reference to the first element of the vector.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::front function is used to access the first element of the vector MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};

  cout<<"The first element of MyVector is: ";
  cout<<MyVector.front();

  cout<<"\n\n100 is added to the first element of the Vector.\n";
  MyVector[0] = MyVector[0] + 100;

  cout<<"Now, The first element of MyVector is: ";
  cout<<MyVector.front();  
  return 0;
}

The output of the above code will be:

The first element of MyVector is: 10

100 is added to the first element of the Vector.
Now, The first element of MyVector is: 110

❮ C++ <vector> Library