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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include <iterator>
#include <iostream>
#include <vector>
#include <algorithm>
// This is a generic template declaration
// Using this requires you to initialize it with something
// like: MyGenerator<double> mygenerator;
template <typename T>
class MyGenerator
{
public:
// These are constructors
// the values after the colon are being initialized
// when the MyGenerate class is constructed
MyGenerator() : start(0),increment(1) { }
MyGenerator(T st, T incr) : start(st),increment(incr) { }
// This overloads the operator () so it can later be used with std::generate
// This is one way to do it
T operator()() {
T value = start;
start += increment;
return value;
}
private:
// These are private member variables
T start;
T increment;
};
// This is an explicit template specialization
// if you want to specialize the generator for the
// double data type
template <>
class MyGenerator <double>
{
public:
MyGenerator() : start(0),increment(1) { }
MyGenerator(double st,double incr) : start(st-incr),increment(incr) { } //**
// this is a second way to do it (notice the difference in the constructor
// initializations
double operator()() {
return start += increment;
}
private:
double start;
double increment;
};
// main function
int main(int argc, char** argv)
{
// initialize the vector to size = 5, fill data with 0.0
// so initial vector is: 0., 0., 0., 0., 0.
std::vector<double> myvector(5,0.0);
// notice the <double> declaration, this is a product
// of using a template, because I have an explicit
// specialization for the double data type the second
// instance of MyGenerator is called, calls constructed noted
// with **
MyGenerator<double> mygenerator(1,1);
// After the line below the data in vector will be 1, 2, 3, 4, 5
std::generate(myvector.begin(),myvector.end(),mygenerator);
// These print the vector to the screen
std::ostream_iterator<double> ite (std::cout," ");
std::copy ( myvector.begin(), myvector.end(), ite );
// Ends the line
std::cout << std::endl;
return 0;
}
|