.front()

Anonymous contributor's avatar
Anonymous contributor
Published Sep 11, 2024
Contribute to Docs

The .front() method returns a reference to the first element in the vector, allowing direct access or modification of the element without creating a separate variable or removing it from the vector.

Syntax

vector_name.front();
  • vector_name: A placeholder representing the name of the vector on which the .front() method is called.

Note: To use vectors, including the vector library is necessary.

Example

In the example below, .front() is used to print the first element of the numbers vector:

#include <iostream>
#include <vector>
int main() {
// Initialize a vector with integers
std::vector<int> numbers = {1, 2, 3, 4};
// Print the first element of the vector using the .front() method
std::cout << numbers.front();
return 0;
}

The output of the above code is:

1

Codebyte Example

Run the following codebyte example to understand how the .front works:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy