std::inserter constructs an insert iterator that inserts new elements into x in successive locations starting at the position pointed by it. It is defined inside the header file
.
An insert iterator is a special type of
output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at a specific position in the container.
Syntax:
std::inserter(Container& x, typename Container::iterator it);
x: Container in which new elements will
be inserted.
it: Iterator pointing to the insertion point.
Returns: An insert_iterator that inserts elements into
x at the position indicated by it.
Output:
v1 = 1 2 3
v2 = 4 1 2 3 5 6
How is it helpful ?
Points to Remember:
-
One of the pitfalls of std::inserter is that it can be used with only those containers that have insert as one of its methods like in case of vector, list and deque, and so on.
- insert() vs std::inserter(): Now, you may be thinking that insert() and std::inserter() are similar, but they are not. When you have to pass an iterator in the algorithm, then you should use inserter() like in above case, while for normally inserting the values in the container, insert() can be used.
-
In place of using std::inserter, we can create a insert_iterator and then use it, as eventually, std::inserter returns a insert_iterator only.