In C++ please.
8. Explain what insert_iterator and inserter() function is. Given the following data structures: vector<int> v1 = {1, 2, 3, 4, 5}; vector<int> v2; Explain the problem with the below code and fix it with inserter() function. copy(v1.begin(), v1.end(), v2.begin());
8). ANSWER :
GIVENTHAT :
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.
Inserting values anywhere : Now, just imagine, if we had to copy value into a container such as a vector, firstly, we had to move elements and then copy, but with the help of std::insert() we can insert at any position with ease.
1.One of the pitfalls of std::inserter is that it can be used with only those containers that have to insert as one of its methods like in case of vector,list and dequeue etc...
2.insert() vs std::insterter():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 algorihtm,then you should use inserter() like in above case,while for normally inserting the values ine the container,insert() and be used.
3.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.
Get Answers For Free
Most questions answered within 1 hours.