views:

14

answers:

2

Hi,

I'd like to partition an interval such as [-1.0, 1.0] into a discrete set of equally spaced points with a specified distance or step-size between each point. For example if the step-size is 0.1 my function would return an array:

-1.0, -0.9, -0.8,...., 0.9, 1.0. 

Now a way of doing using a vector container is a follows:

vector<double> Range;      

double Step = 0.1;

Range.push_back(-1.0); 

for(unsigned int i=0; i<int(2.0/Step); i++)
{
    Range.push_back(Range.back() + Step); 
}

Is there an STL library function I could use?

A: 

Check out the generate function. You will still need to write a function/functor for incrementing, but that is relatively simple and can be reused all the time...

Daren Thomas
A: 

Here is an example using the generate function.

#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <math.h>

using namespace std;

// The step interval
const double step = 0.1;

struct stepInterval {

   double current;

   stepInterval() :
      current (-1.0 - step) {
   }

   double operator()() {
      current += step;
      return current;
   }

} StepInterval;



int main () {
   // Calculate the vector size. Add 1 for zero.
   const int vectorSize = ceil(2.0 / step) + 1;

   // Create the vector
   vector<double> myvector (vectorSize);

   generate (myvector.begin(), myvector.end(), StepInterval);

   cout << "\nmyvector contains:";

   for (vector<double>::iterator it=myvector.begin();
        it!=myvector.end();
        ++it)  {
      cout << " " << *it;
   }
   cout << endl;

   return 0;
}
Sibshops