How to Access the First Element of a Vector in C++?
Last Updated :
09 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5 };
cout << "The first element using front(): "
<< myVector.front() << endl;
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)
Share your thoughts in the comments
Please Login to comment...