Open In App

How to Access the First Element of a Vector in C++?

In C++, vectors are dynamic arrays that were introduced to replace the traditional arrays. In this article, we’ll learn how to access the first element of a vector in C++.

Example



Input:
myVector = {5, 1, 8, 3, 4}

Output:
First element of myVector is: 5

Access the First Element of a Vector in C++

The std::vector class has the std::vector::front() member function which provides a simple way to access the first element of the vector. We can also simply access the first element using its index which is 0 and [] operator.

C++ Program to Access the First Element in a Vector




// C++ Program to demonstrate accessing the first element of
// a vector using front() and [0]
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initializing a vector with some elements
    vector<int> myVector = { 1, 2, 3, 4, 5 };
  
    // Printing the first element using front()
    cout << "The first element using front(): "
         << myVector.front() << endl;
    // Printing the first element using [0]
    cout << "The first element using myVector[0]: "
         << myVector[0] << endl;
  
    return 0;
}

Output

The first element using front(): 1
The first element using myVector[0]: 1

Time Complexity: O(1), as vector provide random access using index.
Auxilary Space: O(1)

Article Tags :