Open In App

Vector front() in C++ STL

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

In C++, the vector front() is a built-in function used to retrieve the first element of the vector. It provides a reference to the first element, allowing you to read or modify it directly.

Let’s take a quick look at a simple example that uses the vector front() method:

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

int main() {
    vector<int> vec = {11, 23, 45, 9};

    // Printing the first element of the vector
    cout << vec.front();
  
    return 0;
}

Output
11

This article covers the syntax, usage, and common example about the vector front() method in C++ STL:

Syntax of Vector front()

v.front();

Parameters:

  • This function does not take any parameter.

Return Value:

  • Returns the reference to the first element of the vector container if present.
  • If the vector is empty, then the behaviour is undefined.

Examples of vector front()

Modify the First Element of the Vector

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

int main() {
    vector<int> v = {5, 10, 15, 20};

    // Modify the first element
    v.front() = 50;

    for (int i : v)
        cout << i << " ";
    return 0;
}

Output
50 10 15 20 

Behaviour of Vector front() with Empty Vectors

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

int main() {
    vector<int> v;

    if (!v.empty()) {
        cout << v.front();
    } else {
        cout << "Vector is empty!";
    }

    return 0;
}

Output
Vector is empty!

Difference Between Vector front() and begin()

The vector front() and begin() both can be used to access the first element of the vector but there are a few differences between them:

FeatureVector front()Vector begin()
PurposeReturns a reference to the first element of the vector.Returns an iterator pointing to the first element of the vector.
Return TypeReference (T&) or constant reference (const T&).vector<T>::iterator type.
UsageOnly used for direct access to the first element.Can be used for iteration and access.
Syntaxv.front();*v.begin();

In short,

  • Use front() for quick, direct access to the first element when no iteration is needed.
  • Use begin() when working with iterators or algorithms.



Next Article
Article Tags :
Practice Tags :

Similar Reads