Search code examples
c++arraysfor-loopshortcut

Setting all items in an array to a number without for loop c++


Right now, to set all items in an array to, say, 0, I have to loop through the entire thing to preset them.

Is there a function or shortcut which can defaultly set all values to a specific number, when the array is stated? Like so:

int array[100] = {0*100}; // sets to {0, 0, 0... 0}

Solution

  • If you want to set all the values to 0 then you can use:

    int array[100] = {0}; //initialize array with all values set to 0
    

    If you want to set some value other than 0 then you can use std::fill from algorithm as shown below:

    int array[100];  //not intialized here
    std::fill(std::begin(array), std::end(array), 45);//all values set to 45