The generate function takes 3 parameters.
The first two are iterators for the particular container (the first one is a start iterator and the second one is the ending iterator).
The third parameter (in this case it is an object of struct c_unique) is what is called a
function object (also known as a
functor).
In basic terms, a function object is something that can be called using the function calling syntax.
Two things spring to mind:
1. A function. (this one is obvious)
2. An object of a class which has an
overloaded function call operator () .
This second method is the the one used in the above example.
Here is the
generate function template definition from MSVC 2008 header files:
1 2 3 4 5 6 7 8 9 10
|
// TEMPLATE FUNCTION generate
template<class _FwdIt,
class _Fn0> inline
void _Generate(_FwdIt _First, _FwdIt _Last, _Fn0 _Func)
{ // replace [_First, _Last) with _Func()
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Func);
for (; _First != _Last; ++_First)
*_First = _Func();
}
|
I have underlined the bits to do with the function object.
As you can see -
*_First =_Func()
- the function object is 'called' using the function call syntax.
With regard to your example.
I have added a function to do the same thing as the struct - andas you can see, they both give the same output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
// class generator: ------- Function Object
struct c_unique {
int current;
c_unique() {current=0;}
int operator()() {return ++current;}
} UniqueNumber;
//Class generator - Function
int generate_number()
{
static int num=1;
return num++;
}
int main()
{
vector<int> myvector (16);
//Using function object
generate (myvector.begin(), myvector.end(), UniqueNumber);
cout << "\nmyvector contains:";
for (unsigned int i = 0; i < myvector.size(); i++)
cout << " " << myvector.at(i);
cout << endl;
//Using a function
generate (myvector.begin(), myvector.end(), generate_number);
cout << "\nmyvector contains:";
for (unsigned int i = 0; i < myvector.size(); i++)
cout << " " << myvector.at(i);
cout << endl;
}
|
For further information - look up the following topics.
1. Operator overloading
2. Function objects.