C++C++11C++14C++17Iterators

Insert Iterators Adapters in C++

Let’s slightly modify the example from The Move Iterator Adapter in C++ post:

In the example above the object of type std::list<std::string> is empty just after the construction and attempt to use std::copy for copying elements from src will cause memory corruption is case when the given src is not empty. However, the standard library provides special adapters which are template classes: std::back_insert_iterator, std::front_insert_iterator and std::insert_iterator. These adapters appends, prepends and inserts the elements to a corresponding container by using push_back(), push_front() and insert() methods accordingly, rather than overwriting the existing elements in the destination container. In other words, the destination container grows in size by one element whenever a value is written through an insert iterator adapter. These adapters can be conveniently created by using function templates std::back_inserter(), std::front_inserter() and std::inserter(), for example:

Finally, please note, insert adapters are output iterators (see Categories of Iterators in C++) and thus it’s not possible to read through them.

close

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

Related posts
C++ComponentsDatabaseIntroduction to C++Language FeatureLearn C++

Get To Know The Powerful C++ Data Bindings In Windows Apps

C++Introduction to C++Language FeatureLearn C++

How to Create a New Windows FMX Static Library In C++

C++C++11C++14C++17Introduction to C++Learn C++

How To Use C++ front() And back() Methods Of Vectors

C++Generic ProgrammingIntroduction to C++Language FeatureLearn C++

5 Things You Need To Know About Optimization In C++ Builder

ru_RURussian