1

I'm making a program that uses the std::generate_n function. I can get it to work fine with arrays, but I can't figure out how to make it work with a list container. Here is what I have:

#include <iostream>
#include <algorithm>
#include <list>
using namespace std;

int current = 0;
int UniqueNumber () { return ++current; }

int main ()
{
    list<int> L;
    list<int>::iterator it;

    generate_n (L.begin(), 9, UniqueNumber);

    cout << "list contains:";
    for (it=L.begin(); it!=L.end(); ++it)
    cout << ' ' << *it << '\n';

    return 0;
}

The output only displays "list contains:" with nothing after that. I know my output loop functions correctly because I tried it manually with the insert() method, so the problem is something with the generate_n function. I think I'm passing the arguments wrong. Anyone know what I did?

tshepang
  • 12,111
  • 21
  • 91
  • 136
user1804208
  • 165
  • 2
  • 4
  • 9
  • [Avoid `using namespace std`](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Manu343726 Oct 05 '13 at 23:11
  • Use `std::generate_n(std::back_inserter(L), 9, UniqueNumber)`, and unless you have future plans for `current` in the global namespace, you may as well make it static to `UniqueNumber()`. – WhozCraig Oct 05 '13 at 23:14

2 Answers2

3

You want to use an insert-iterator to add items to your list:

generate_n (back_inserter(L), 9, UniqueNumber);

Be sure to #include <iterator> to use it. Another possibility would be to use std::iota:

list<int> L(10);
std::iota(L.begin(), L.end(), 1);

Oh, and to display the contents of the list, you probably want:

std::copy(L.begin(), L.end(), ostream_iterator<int>(std::cout, "\n"));

or (in C++11):

for (auto i : L)
    std::cout << ' ' << i << '\n';
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

generate_n doesn't insert, it just dereferences and assigns.

See the below possible implementation of generate_n (copied from here):

template< class OutputIt, class Size, class Generator >
OutputIt generate_n( OutputIt first, Size count, Generator g )
{
    for( Size i = 0; i < count; i++ ) {
        *first++ = g();
    }
    return first;
}

So you need to make sure the list is the appropriate size before you call it.

So, change:

list<int> L;

to:

list<int> L(9);
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138