std::front_inserter() is a utility function in the C++ Standard Library that creates a special output iterator for inserting elements at the beginning of a container. It is defined in the <iterator> header file.
- Inserts elements at the front of a container using push_front().
- Allows STL algorithms to insert elements instead of overwriting existing ones.
#include <iostream>
#include <algorithm>
#include <deque>
#include <iterator>
using namespace std;
int main() {
deque<int> v1 = {1, 2, 3};
deque<int> v2 = {4, 5, 6};
copy(v1.begin(), v1.end(),
front_inserter(v2));
for (int x : v2)
cout << x << " ";
}
Output
3 2 1 4 5 6
Explanation: Since elements are inserted at the front, the copied elements appear in reverse order.
Syntax
std::front_inserter(Container& container);
Parameters: container - The container in which elements will be inserted at the beginning.
Return Value: Returns a std::front_insert_iterator object associated with the given container.
Working of std::front_inserter()
std::front_inserter() creates a special output iterator that inserts elements using the container's push_front() member function.
- Creates a front_insert_iterator for the specified container.
- Every assignment to the iterator internally calls push_front().
- Allows STL algorithms to insert elements at the beginning of a container.
Internally:
*iterator = value;
is equivalent to:
container.push_front(value);
For example:
auto it = front_inserter(dq);
*it = 10; // dq.push_front(10)
*it = 20; // dq.push_front(20)
After these operations 20 and 10 is stored in the container.
Example: Reversing a Container
Since every element is inserted at the front, std::front_inserter() naturally reverses the order of copied elements.
#include <iostream>
#include <algorithm>
#include <deque>
#include <iterator>
using namespace std;
int main() {
deque<int> v1 = {1, 2, 3, 4, 5};
deque<int> v2;
copy(v1.begin(), v1.end(),
front_inserter(v2));
for (int x : v2)
cout << x << " ";
}
Output
5 4 3 2 1
Containers Supported by std::front_inserter()
std::front_inserter() can only be used with containers that provide the push_front() member function. Supported Containers are:
- std::deque
- std::list
Unsupported Containers are:
- std::vector
- std::array
- std::set
- std::map
Advantages of Using std::front_inserter()
std::front_inserter() provides several benefits when working with STL algorithms and containers:
- Automatically inserts elements at the beginning of a container.
- Eliminates the need to manually call push_front().
- Allows algorithms such as std::copy() to work with empty containers.
- Can be used to efficiently create reversed sequences.
push_front() vs std::front_inserter()
| push_front() | std::front_inserter() |
|---|---|
| Inserts elements directly into a container. | Creates an iterator that inserts elements at the front. |
| Used in ordinary container operations. | Used with STL algorithms. |
| Requires explicit calls. | Performs insertion automatically. |