Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly create arrays in C++

Tags:

c++

arrays

matlab

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.

like image 547
Paradox Avatar asked Feb 11 '15 06:02

Paradox


1 Answers

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);
like image 96
Jerry Coffin Avatar answered Nov 03 '22 10:11

Jerry Coffin