What is the vector.front() function in C++?
In this shot, we will learn about vector::front() function in C++.
Introduction
The vector::front() function is available in the <vector> header file. This function returns a reference to the first element in the vector.
If we call the front() function on a vector that contains no elements, then we will get a segmentation fault error.
Syntax
The syntax of the vector::front() function is given below:
T& front();
Parameter
The vector::front() function does not accept any parameters.
Return
It returns a reference of the template-type object that points to the first element of the vector.
Code
Let’s have a look at the code now.
#include <iostream>#include <vector>using namespace std;int main(){vector<int> vec;// cout << " The Frontmost element of an empty vector is: " << vec.front();vec.push_back(3);vec.push_back(4);vec.push_back(5);vec.push_back(6);vec.push_back(2);cout << " The Frontmost element of the vector is: " << vec.front();return 0;}
Explanation
-
In line 1, we include the C++ standard header file for input/output stream (
iostream) which is used to read and write from streams. -
In line 2, we include the header file for C++ standard
vector, which includes all the functions and operations related to the vector container. -
In line 3, we use the standard (
std) namespace that means we use all the things within thestdnamespace. -
In line 7, we declare the integer type vector container named
vec. -
In line 9, we call the
front()function on an empty vector. If you uncomment the line, then you will get a segmentation fault error as there is no element in the vector. -
From line 11 to 15, we push back the different elements to the vector container
vec. -
In line 17, we print the result of the function
front(), which returns the foremost element of the vector container and in this example, is the front-most element. Hence the output is 3.
So, in this way, we can easily get the first element present in the vector.