.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
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 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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours