Wednesday, October 16, 2024

back_insert_iterator

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

Details
A back-insert_iterator is a special output iterator which can be  generated from the container that supports push_back() operation. such as standard containers vectordeque and list.

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

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

Operation
An back_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 back_insert_iterator does nothing.

This can be clearly seen in the example below. 
vector<int> v{1,2,3,4};
back_insert_iterator<vector<int> > backiter ( v );

//v:{1,2,3,4,6}
*backiter = 6;

//v:{1,2,3,4,6,7}
backiter = 7;

Functionality

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

Example:
vector<int> v{1, 2, 3, 4, 5};
back_insert_iterator<vector<int>> backiter (v);


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

Example:
vector<int> v{1,2,3,4};
back_insert_iterator<vector<int> > backiter ( v );

//v:{1,2,3,4,6}
*backiter = 6;

//v:{1,2,3,4,6,7}
backiter = 7;

back_inserter
An utility function to create a back_insert_iterator from a container that supports push_back() method such as vector, deque, list.

Syntax
The syntax is as below. Template parameter Container represents the container for which 
back_inserter_iterator is created. Container represents must support push_back() function as in vector, deque and list.
template < class Container > 
back_insert_iterator<Container >  back_inserter( Container& c );

The following example shows its usage.
vector<int> v{1,2,3,4}, v2;
//same as 
//for_each(begin(v),end(v),[&v2](int i){v2.push_back(i);});
//v2:{1,2,3,4}
copy (v.begin(),v.end(),back_inserter(v2));


No comments:

Post a Comment