pre-allocated container vs. insert_iterator

Y

yuvalif

Hi,
I wanted to create a simple example of why using insert_iterator and
not a pre-allocated container. When writing a function that should
fill data into someone else's container.
I would be happy to hear your comments on the example (or if you have
a better one...):

#include <list>
#include <iterator>
#include <iostream>
#include <stdlib.h>

template <typename T, T (*Generate)(), typename OutputIterator>
struct populate
{
void Do(unsigned int n, OutputIterator it)
{
while (n > 0)
{
*it = Generate();
++it;
--n;
}
}

void Do(unsigned int n, OutputIterator it_start, const
OutputIterator it_end)
{
while (n > 0)
{
*it_start = Generate();
++it_start;
--n;
if (it_start == it_end)
{
std::cout << "iterator overflow" <<
std::endl;
return;
}
}
}
};

float generate_random()
{
return rand();
}

void with_allocated_container()
{
typedef std::list<float> FloatList;
typedef std::list<float>::iterator FloatListIterator;
typedef populate<float, generate_random, FloatListIterator>
populate_float_list;

FloatList my_list;

for (unsigned int i = 0; i < 10; ++i)
{
my_list.push_back(0.0);
}

FloatListIterator it = my_list.begin();
populate_float_list my_populate;
my_populate.Do(15, it, my_list.end());

for (it = my_list.begin(); it != my_list.end(); ++it)
{
std::cout << *it << std::endl;
}
}

void with_inserter()
{
std::cout << "with_inserter" << std::endl;
typedef std::list<float> FloatList;
typedef std::list<float>::iterator FloatListIterator;
typedef std::insert_iterator< std::list<float> >
FloatListInserter;
typedef populate<float, generate_random, FloatListInserter>
populate_float_list;

FloatList my_list;

FloatListIterator it = my_list.begin();
populate_float_list my_populate;
my_populate.Do(15, std::inserter(my_list, it));

for (it = my_list.begin(); it != my_list.end(); ++it)
{
std::cout << *it << std::endl;
}
}


int main()
{
with_inserter();
with_allocated_container();
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top