How to use std::front_inserter in C ++
In this post, we are going to learn about the standard function in C++ std::front_inserter. While it is declared or defined in the header file it can be applied on the container to create a front-insert iterator to in insert elements from the beginning.
What is std::front_insert?
std::front_insert is an output iterator that allows inserting a new element at the front of the container. Instead of copying elements as other containers provide the copy function. It returns the std::front_insert_iterator. It differs from push_front() as this function only adds a new element at the beginning but std::front_inserter adds element by creating an iterator and then adding it to a container. This function or method is used on containers having push_front() function like list and deque.
Syntax:
std::front_inserter (Container& z); z: container to which element is added.
Program:
#include<iostream> #include<list> #include<iterator> using namespace std; int main() { int first[] = { 11, 55, 88, 87}; std::list<int> d1 (first, first + sizeof(first) / sizeof(int) ); int second[] = { 23, 52, 74, 31, 86}; std::list<int> d2 (second, second + sizeof(second) / sizeof(int) ); std::copy(d1.begin(),d1.end(),std::front_inserter(d2)); cout<<" d1= "; for (std::list<int>::iterator it = d1.begin(); it != d1.end(); it++) std::cout << *it << ' '; cout<<"\n d2= "; for (std::list<int>::iterator it = d2.begin(); it != d2.end(); it++) std::cout << *it << ' '; return 0; }
In the above program, we have declared a standard list, iterator. We have declared two arrays named first and second and then converted it into a list. Using std:: copy we copied all list elements form d1 to d2 while using front_inserter thus all the elements are copied at the beginning of d1 and thud we printed them separately. Thus this function returns the std::front_inserter_iterator.
OUTPUT:
d1= 11 55 88 87
d2= 87 88 55 11 23 52 74 31 86
Leave a Reply