I've been used to using Python or Matlab where I could create a list like:
min = 5;
step = 2;
max = 16;
Range = min:step:max;
and Range would be the list [5,7,9,11,13,15].
Is there an equivalently simple way to generate a list like "Range" in C++? So far the simplest thing I can think of is using a for loop but that is comparatively quite tedious.
C++ doesn't supply such a thing, either in the language or the standard library. I'd write a function template to look (roughly) like something from the standard library, something on this order:
namespace stdx {
template <class FwdIt, class T>
void iota_n(FwdIt b, size_t count, T val = T(), T step = T(1)) {
for (; count; --count, ++b, val += step)
*b = val;
}
}
From there it would look something like this:
std::vector<int> numbers;
stdx::iota_n(std::back_inserter(numbers), 6, 5, 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With