C++ .front()
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
vectorlibrary 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 integersstd::vector<int> numbers = {1, 2, 3, 4};// Print the first element of the vector using the .front() methodstd::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:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours