C++ std::list::emplace_front
The std::list::emplace_front
function inserts a new element at the beginning of the list. This function constructs the element in place, which avoids unnecessary copies or moves. It is a more efficient alternative to push_front
when constructing elements directly.
Syntax of std::list::emplace_front
template <class... Args>
void emplace_front(Args&&... args);
Parameters
Parameter | Description |
---|---|
args... | Arguments to forward to the constructor of the element being emplaced. |
Return Value
This function does not return a value. It modifies the list by adding a new element at the beginning.
Exceptions
The function may throw exceptions if memory allocation fails or if the constructor of the element being emplaced throws an exception.
The std::list::emplace_front
function ensures strong exception safety. If an exception is thrown (e.g., due to memory allocation failure or the constructor of the element throwing an exception), the state of the list remains unchanged.
Examples for std::list::emplace_front
Example 1: Adding a Single Element to the Front
This example demonstrates how to use emplace_front
to add a single element to the front of a list:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {20, 30, 40};
myList.emplace_front(10); // Add 10 to the front of the list
std::cout << "List contents: ";
for (const auto& elem : myList) {
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- A
std::list
namedmyList
is initialized with the elements{20, 30, 40}
. - The function
myList.emplace_front(10)
is used to add the element10
to the front of the list. - The program uses a range-based
for
loop to iterate over all elements of the list, and print them to output.
Output:
List contents: 10 20 30 40
Example 2: Emplacing Complex Objects
This example demonstrates how to use emplace_front
to construct and add a complex object to the front of a list:
#include <iostream>
#include <list>
#include <string>
struct Person {
std::string name;
int age;
Person(const std::string& name, int age) : name(name), age(age) {}
};
int main() {
std::list<Person> people;
people.emplace_front("Arjun", 25); // Emplace a Person object at the front
for (const auto& person : people) {
std::cout << person.name << " (" << person.age << " years old)" << std::endl;
}
return 0;
}
Explanation:
- A
Person
struct is defined with two members:name
: A string representing the person’s name.age
: An integer representing the person’s age.- constructor that initializes its members using parameters:
- A
std::list
ofPerson
objects namedpeople
is created and initially empty. - The function
emplace_front
is used to construct and add aPerson
object to the front of the list:people.emplace_front("Arjun", 25)
: Constructs aPerson
object with the name"Arjun"
and age25
directly in the list without creating a temporary object.
- A range-based for loop is used to iterate over the list:
Output:
Arjun (25 years old)