将数组中的所有项目设置为一个数字而无需 for 循环 C++

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

现在,要将数组中的所有项目设置为 0,我必须遍历整个项目以预设它们。

是否有函数或快捷方式可以在声明数组时将所有值默认设置为特定数字?像这样:

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

如果你想将所有值设置为0那么你可以使用:

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

如果您想设置 0 以外的其他值,那么您可以使用 算法 中的 std::fill,如下所示:

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

应该做的工作 请参考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

今后您应该使用 std::array 而不是 C 风格的数组。所以这变成:

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

你应该使用向量,它比数组更灵活。

#include <iostream>
#include <vector>

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

试试运行这个: https://onlinegdb.com/2qy1sHcQU

如果您想使用函数的 return 值初始化数组:

#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 );
}