Open In App

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

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to access the first element of vector in C++.

The most efficient way to access the first element of vector is by using vector front() function. Let’s take a look at a simple example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {3, 5, 9, 7};

    // Accessing the first element
    cout << v.front();
  
    return 0;
}

Output
3

Explanation: The front() function returns the reference to the first element of vector.

C++ also provides some other methods to access the first element of vector. They are as follows:

Using Vector [] Operator

The index of the first element in vector is 0, so we can access element at first element by index using vector operator [].

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {3, 5, 9, 7};

    // Accessing the first element
    cout << v[0];
  
    return 0;
}

Output
3

Using Vector at()

The vector at() method can also be used to access the first element of the vector by using its index. The advantage of this method is that if the vector is empty then it throws std::out_of_range exception.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {3, 5, 9, 7};

    // Accessing the first element
    cout << v.at(0);
  
    return 0;
}

Output
3

Using Vector begin()

The vector begin() method returns an iterator pointing to the first element of vector which can be then accessed by dereferencing the iterator.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {3, 5, 9, 7};

    // Accessing the first element
    cout << *v.begin();
  
    return 0;
}

Output
3

Using Vector rend()

The vector rend() is an iterator pointing to theoretical element that is just before the first element of vector. On decrementing this iterator by 1, it will point to first element of vector which can be then accessed by dereferencing the iterator.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {3, 5, 9, 7};

    // Accessing the first element
    cout << *--v.rend();
  
    return 0;
}

Output
3

Next Article
Article Tags :
Practice Tags :

Similar Reads