How to parameterize an interval in C++

When a case is parameterized within a C++ test application, this short function can help generate an interval ‘[a,b]’ with ‘N’ elements.

Step-by-step guide

std::vector<double> linspace(double start, double end, int size)
    std::vector<double> result(size, 0);
    std::generate(result.begin(), result.end(),
                  [n = 0, start, end, result] () mutable
                  { return (n++ * (end - start)) / (result.size() - 1);});
    return result;

This returns by value, but the NRVO should take care of the in-place construction of ‘result’. Running in FULLDEBUG mode might be slower though, for very large ‘N’.

See also