A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/vector-front-in-cpp-stl/ below:

Vector front() in C++ STL

Vector front() in C++ STL

Last Updated : 21 Nov, 2024

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;
}

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

Syntax of Vector front()

v.front();

Parameters:

Return Value:

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;
}
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;
}
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,



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4