My question is simple here:
How to generate a vector [1, 2, 3 ..., N] efficently?
Any speed up idea would be okay. (SIMD?)
Assume to build such a vector in runtime, because N is known only in runtime.
1 2 3 4 5
/// My current idea
std::vector<uint64_t> vec;
vec.reserve(N);
vec.resize(N);
std::generate(vec.begin(), vec.end(), [n = 0] () mutable { return n++; });
if you are declaring it where you know N, just do it all at once:
std::vector<uint64_t> vec(N);
what is the scenario?
is this in a function call, and you re-created this thing frequently?
Does N change?
if its 1-n, maybe std::iota is faster, but I do not know. It may be the same.
what are you doing? You may not need to store these at all if 1-n is really the answer, and not an example.
grumbles about how I wasted 5 minutes trying to find iota in <algorithm>, not knowing it was defined in <numeric>
CakeByTheOcean, you should either reserve and push_back, or do resize (or construct directly). I imagine both will be about equal in performance. But doing a reserve and then a resize is pointless. It's not really harmful, just unnecessary.
btw, if you look into the assembly generated with optimization turned on, I believe compilers will generate simd instructions. https://godbolt.org/
But above all, measure. Do a measurement of which implementation is the most efficient, and at different values of n.
Well... if you absolutely positively must optimize the process of setting each element of an array (or vector) to an increasing sequence, you could do something like this: