Standard C++ Library Class Reference
class factorial : public unary_function<Arg, Arg>
{
public:
Arg operator()(const Arg& arg)
{
Arg a = 1;
for(Arg i = 2; i <= arg; i++)
a *= i;
return a;
}
};
int main()
{
//Initialize a deque with an array of ints
int init[7] = {1,2,3,4,5,6,7};
deque<int> d(init, init+7);
//Create an empty vector to store the factorials
vector<int> v((size_t)7);
//Transform the numbers in the deque to their factorials and
// store in the vector
transform(d.begin(), d.end(), v.begin(), factorial<int>());
//Print the results
cout << "The following numbers: " << endl << " ";
copy(d.begin(),d.end(),ostream_iterator<int>(cout," "));
cout << endl << endl;
cout << "Have the factorials: " << endl << " ";
copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
return 0;
}
Output :
The following numbers:
1 2 3 4 5 6 7
Have the factorials:
1 2 6 24 120 720 5040
Warnings
If your compiler does not support default template parameters, then you need to always supply
the Allocator template argument. For instance, you'll have to write :
vector<int, allocator> and deque<int, allocator>
instead of :
vector<int> and deque<int>