【问题标题】:Setting all items in an array to a number without for loop c++ [duplicate]将数组中的所有项目设置为没有for循环c ++的数字[重复]
【发布时间】:2022-01-13 03:22:32
【问题描述】:

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

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

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

【问题讨论】:

  • 如果你可以灵活地使用std::vector,那么你可以在构造过程中像std::vector<int> v (100 /* length */, 42 /* initial value */);一样初始化
  • {0*100} 看起来有点奇怪。一方面,0 * 100 == 0 并且正确 (answer of Denise)。另一方面,看起来重复 0 是为了表达。那是行不通的。而且,顺便说一句。 0 是这种方式的数组初始值设定项的唯一可能值。
  • 这只是一个例子。
  • 这只是一个例子。 是的,但有点令人困惑...... ;-)
  • @SkyriderFeyrs 在 python 中是 [0]*3 -> [0, 0, 0] 而不是 [0*100] -> [0]。不相关:在 python 中的列表上使用乘法时要小心,你会成为changes in sublist are relected across the list 的受害者

标签: c++ arrays for-loop shortcut


【解决方案1】:
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

【讨论】:

  • 这个只设置为0...
  • 是的,对不起,根据你的例子,我认为具体的数字应该是 0。 int arr[100] = {1};导致数组的第一个位置为 1,其余 99 个位置为 0。
【解决方案2】:

如果您想将所有值设置为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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      如果要使用函数的返回值来初始化数组:

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

      【讨论】:

        【解决方案5】:

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

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

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

        【讨论】:

        • 我很确定这只会初始化第一个元素。 godbolt.org/z/36e3EYKE1
        • 是的,只有第一个元素。
        • @Jellyboy 你说得对,让我编辑
        猜你喜欢
        • 2022-10-13
        • 2018-02-14
        • 2020-12-07
        • 2019-02-16
        • 2017-02-03
        • 1970-01-01
        • 2018-03-26
        • 2019-04-14
        • 1970-01-01
        相关资源
        最近更新 更多