-
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
Code:
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <iterator>
struct g
{
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, " "));
getchar();
}
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?
Thanks
-
It uses the instance you pass to it.