C++ .front()

Christine_Yang's avatar
Published May 23, 2022Updated Sep 12, 2025
Contribute to Docs

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.

  • 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

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 queue
std::queue<std::string> colors;
// Inserting elements into the queue
colors.push("Red");
colors.push("Blue");
colors.push("Green");
colors.push("Yellow");
// Print the first element of the queue
std::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 queue
q.pop();
}
return 0;
}

Here is the output:

Alice
Bob
Charlie

Codebyte Example: Modifying the First Element Using C++ .front()

This codebyte example uses C++ .front() to modify the first element of the queue:

Code
Output
Loading...

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.

All contributors

Contribute to 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