Initialize all the elements of an array to the same number

There are many ways to fill an array with the same value, and if you are concerned about performance then you need to measure.

C++ has a dedicated function for filling an array with a value, and I would use this (after #include <algorithm> and #include <iterator>):

std::fill(std::begin(A), std::end(A), 3);

You shouldn’t underestimate what optimizing compilers can do with something like this.

If you are interested in seeing what the compiler does, then Matt Godbolt’s Compiler Explorer is a very good tool if you’re prepared to learn a little bit of assembler. As you can see from here, compilers can optimize the fill call to twelve (and a bit) 128-bit stores with any loops unrolled. Because compilers have knowledge of the target environment they can do this without encoding any target-specific assumptions in the source code.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)