back_inserter explained

back_inserter stl iterator class is an adapter class. So what is an adapter? If you buy a laptop in India and then take it to the US/Europe, plugs given won’t fit into the sockets there, so what we do is buy an adapter, which adapts our laptop’s plug to the sockets there. Adapter pattern based class adapts an existing functionality to a close relative of it’s own. Similarly back_inserter adapts a normal iterator to a more dynamic one, which means inserts an element into a vector by increasing it’s size i.e. push_back.

Back_inserter can be given as an iterator to stl algorithms. Lets take a case of reading a file. We don’t know how much bytes are there in a file, so what we do is iterate through to the end of the file along with inserting read in bytes to a vector. This functionality requires a loop, but with back_inserter, we just need one line of code. Here is a demo…

[sourcecode language=’cpp’]typedef std::vector BytesVector;
BytesVector FileBytes;
std::ifstream file( “C:\umdhlog.log” );
std::copy( std::istream_iterator< char >( file ), // Starts iterating file
           std::istream_iterator< char >(), // Dummy param to denote EOF
           back_inserter( FileBytes )); // Inserts elements to a vector[/sourcecode]

Last parameter to std::copy is the key, it’s a back_inserter object. Also note that we’ve given an empty vector and not a resized one. Key to this behavior is the way in which back_inserter behaves, when it inserts an element to a vector it in fact does a push_back. Had we given FileBytes.begin() instead of back_inserter( FileBytes ) there will be a crash.

Another example to fill in a vector with hundred random numbers using back_inserter…

[sourcecode language=’cpp’]typedef std::vector IntVector;
IntVector Ints;
std::generate_n(std::back_inserter( Ints ), 100, rand);[/sourcecode]

A close relative of back_inserter is front_inserter used mainly with std::lists.

Appreciate your comments...