Thread: std::generate algorithm

  1. #1
    Registered User subdene's Avatar
    Join Date
    Jan 2002

    std::generate algorithm

    Hi All,

    I have just been having a mess around with the function call operator and the generate algorithm. When I first saw the output of this which is:

    0 1 2 3 4 5 6 7 8 9

    #include "stdafx.h"
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    struct g
    		n = 0;
    	int operator()() 
    		return n++; 
            int n;
    int main()
            int a[10];
    	int size = (sizeof(a) / sizeof(a[0]));
            std::generate(a, a + size, g());
            std::copy(a, a+10, std::ostream_iterator<int>(std::cout, " "));
    My natural instinct was to think that this would be 0 0 0 0 0 0 etc...
    However, it looks like the implementation of the generate algorithm creates only one instance of type g, then uses that same instance for subsequent iterations. Is this correct?

    Be a leader and not a follower.

  2. #2
    The larch
    Join Date
    May 2006
    It uses the instance you pass to it.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 2 Matrix to generate a 3rd one
    By danielldf in forum C Programming
    Replies: 2
    Last Post: 03-20-2011, 06:19 PM
  2. generate number
    By cheeta in forum C Programming
    Replies: 9
    Last Post: 05-03-2010, 07:49 AM
  3. Generate board
    By oleg174 in forum C Programming
    Replies: 1
    Last Post: 03-07-2010, 06:26 AM
  4. generate svg
    By stabu in forum C Programming
    Replies: 3
    Last Post: 02-25-2010, 12:42 PM
  5. Trying to generate a bus error
    By Tommo in forum C Programming
    Replies: 4
    Last Post: 08-22-2007, 05:37 AM