C++ std::list::pop_front
The std::list::pop_front function removes the first element from a std::list. This operation reduces the size of the list by one, but does not return the removed element. The function is commonly used when processing elements from the front of a list in FIFO (First In, First Out) operations.
Syntax of std::list::pop_front
void pop_front();
Parameters
This function does not accept any parameters.
Return Value
The function does not return any value. It removes the first element of the list and adjusts the size accordingly.
Exceptions
The std::list::pop_front function does not throw exceptions itself. However, accessing the function on an empty list does not throw an exception, but calling it on an empty list results in undefined behavior.
To avoid undefined behavior, always ensure the list is not empty before calling pop_front. This can be done using the empty() method.
Examples for std::list::pop_front
Example 1: Removing Elements from the Front
This example demonstrates how to use pop_front to remove elements from the front of a list:
Program
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30, 40};
myList.pop_front(); // Remove the first element (10)
std::cout << "List contents after pop_front: ";
for (const auto& elem : myList) {
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- A
std::listnamedmyListis initialized with the elements{10, 20, 30, 40}. - The
pop_frontfunction is called, removing the first element10. - The remaining elements of the list are printed using a range-based
forloop.
Output:
List contents after pop_front: 20 30 40
Example 2: Handling Empty List
This example demonstrates how to safely call pop_front on a list and avoid undefined behavior:
Program
#include <iostream>
#include <list>
int main() {
std::list<int> myList;
if (!myList.empty()) {
myList.pop_front();
} else {
std::cout << "List is empty, cannot call pop_front." << std::endl;
}
return 0;
}
Explanation:
- A
std::listnamedmyListis created and is initially empty. - The
empty()method is used to check if the list contains elements before callingpop_front. - If the list is empty, a message is printed to indicate that the operation cannot be performed.
Output:
List is empty, cannot call pop_front.
