Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting all array elements to an integer

Tags:

c++

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?

like image 621
John Avatar asked Nov 28 '22 01:11

John


1 Answers

Your code has two paths in the loop, depending on each value:

  1. Read from array, comparison, and branch
  2. Read from array, comparison, and write

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.

like image 103
Jon Reid Avatar answered Dec 10 '22 03:12

Jon Reid