I have an array,
int a[size];
I want to set all the array elements to 1
because some of the indexes in the array are already set to 1
so would it better checking each element using a conditional statement like,
for (int index = 0; index < size; index++)
{
if (a[index] != 1)
a[index] = 1;
}
or set all the indexes no matter what. what would be the difference?
Your code has two paths in the loop, depending on each value:
That's not worth it. Just write.
If you want, you can do the same by calling
std::fill(a, a + size, 1);
If the array is of type char
instead of int
, it will likely call memset
. And platform-specific implementations of fill
can offer the compiler optimization hints.
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