Wednesday, October 16, 2024

front_insert_iterator

Overview
The STL algorithms usually overwrite elements of the range passed to them as parameters. Instead, sometimes it's useful to prepend new elements to the range. front_insert_iterator designed exactly to do it.

Details
A front_insert_iterator is a special output iterator which can be  generated  for containers that support push_front()  method as in the standard containers  deque and list.

Syntax
The syntax is as below. Template parameter Container represents the container that is updated. 
template < class Container > 
class  front_insert_iterator;

Members
 It defines following types.
member typedefinition
conainer_typeContainer
iterator_categoryoutput_iterator_tag
value_typevoid
difference_typevoid
pointervoid
referencevoid

Operation
An front_insert_iterator supports three operators *, ++ and =. 
The assignment operator, used both during dereferencing or directly, causes the container to expand by one element. For example, both *i = x and i=x adds a new element.
Dereferencing operator does nothing.
Both pre and post Increments the front_insert_iterator does nothing.

This can be clearly seen in the example below. 
list<int> v{3,4};
front_insert_iterator<list<int> > frontiter ( v );

//v:{2,3,4}
*frontiter = 2;

//v:{1,2,3,4}
frontiter = 1;

Functionality

Constructors
NameDescription
front_insert_iterator(Container& c)
Initializes the underlying pointer to the container to addressof(c).

Example:
list<int> v{1, 2, 3, 4, 5};
front_insert_iterator<list<int>> frontiter (v);


Overloaded operators
NameExample
reference operator*() No Operation.
  1. front_insert_iterator& operator++()
  2. front_insert_iterator operator++(int)
No Operation.
pointer operator=() 
Prepends new element.

Example:
list<int> v{3,4};
front_insert_iterator<list<int> > frontiter ( v );

//v:{2,3,4}
*frontiter = 2;

//v:{1,2,3,4}
frontiter = 1;


front_inserter
An utility function to create a front_insert_iterator from a container that supports push_front() method such as  deque, list.

Syntax
The syntax is as below. Template parameter Container represents the container for which 
front_inserter_iterator is created. Container represents must support push_front() function as in  deque and list.
template < class Container > 
front_insert_iterator<Container >  front_inserter( Container& c );

The following example shows its usage.
list<int> v{1,2,3,4}, v2;
//same as 
//for_each(rbegin(v),rend(v),[&v2](int i){push_front(i);});
//v2:{1,2,3,4}
copy (v.rbegin(),v.rend(),front_inserter(v2));




No comments:

Post a Comment