C++ .front()
The C++ .front() method is used to access the element at the front of the queue. Unlike .back(), which gives the last element, .front() allows programmers to directly work with the element at the beginning without removing it.
C++ .front() Syntax
queueName.front();
Parameters:
The C++ .front() method takes no parameters.
Return value:
Returns a reference to the element at the front of the queue.
Example 1: Basic Usage of C++ .front()
This example uses C++ .front() to access the first element of the queue:
#include <iostream>#include <queue>int main() {// Declaring a queuestd::queue<std::string> colors;// Inserting elements into the queuecolors.push("Red");colors.push("Blue");colors.push("Green");colors.push("Yellow");// Print the first element of the queuestd::cout << colors.front();}
Here is the output:
Red
Example 2: Using C++ .front() with .pop()
Until the queue is empty, this example uses C++ .front() to return the first element of the queue before it is removed using .pop():
#include <iostream>#include <queue>using namespace std;int main() {queue<string> q;q.push("Alice");q.push("Bob");q.push("Charlie");while (!q.empty()) {cout << q.front() << endl;// Remove the first element of the queueq.pop();}return 0;}
Here is the output:
AliceBobCharlie
Codebyte Example: Modifying the First Element Using C++ .front()
This codebyte example uses C++ .front() to modify the first element of the queue:
Frequently Asked Questions
1. What is the .front() function of queue in C++?
The .front() function of queue in C++ returns the element at the beginning of the queue without removing it.
2. How do you get the front of the queue in C++?
To get the front of the queue in C++, the .front() method can be used:
q.front();
3. What does C++ .front() return?
The C++ .front() method returns the first element of the queue, which can then be used and modified.
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