Home > Blockchain >  Setting all items in an array to a number without for loop c
Setting all items in an array to a number without for loop c

Time:12-08

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}

CodePudding user response:

int array[100] = {0}; 

should do the job Please refer to cppreference

int a[3] = {0}; // valid C and C   way to zero-out a block-scope array
int a[3] = {}; // invalid C but valid C   way to zero-out a block-scope array

CodePudding user response:

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

CodePudding user response:

Going forward you should use std::array instead of C-style arrays. So this become:

std::array<int,100> array;
array.fill(0);

CodePudding user response:

If you want to initialize the array using a function's return value:

#include <algorithm>

int generateSomeValue( )
{
    int result { };
    // some operations here to calculate result

    return result;
}

int main( )
{
    int array[ 100 ];
    std::generate( std::begin( array ), std::end( array ), generateSomeValue );
}

CodePudding user response:

You should use vectors, which are more flexible than array.

#include <iostream>
#include <vector>

int main()
{
std::vector<int>v(100,10); // set 100 elements to 10
}

Try running this: https://onlinegdb.com/2qy1sHcQU

  • Related