Vector front() in C++ STL
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:
#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:
Table of Content
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
#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
#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:
Feature | Vector front() | Vector begin() |
---|---|---|
Purpose | Returns a reference to the first element of the vector. | Returns an iterator pointing to the first element of the vector. |
Return Type | Reference (T&) or constant reference (const T&). | vector<T>::iterator type. |
Usage | Only used for direct access to the first element. | Can be used for iteration and access. |
Syntax | v.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.