【问题标题】:what are all the different ways to initialize a c++ array?初始化 C++ 数组的所有不同方法是什么?
【发布时间】:2021-12-31 06:50:38
【问题描述】:
class Solution {
public:
    int numSquares(int n) {
        int dp[n+1];
        for(int i=0;i<=n;i++) dp[i]=0;  //initializing all the elements to zero
        for(int i=1;i<=n;i++){
            int t = INT_MAX;
            for(int j=1;j<=(int)sqrt(i);j++){
                t = min(t,dp[i-j*j]);
            }
            dp[i] = t+1;
        }
        return dp[n];
    }
};

上述方法工作得很好,但是当我尝试像这样初始化数组时

int dp[n] = {0}  //variable sized array cannot be initialized

我收到了无法初始化可变大小数组的错误。 有什么原因要初始化这个数组而不是使用 for 循环,请解释我为什么会收到这个错误?

【问题讨论】:

    标签: c++ arrays


    【解决方案1】:

    问题是在 C++ 中,数组的大小必须是一个编译时间常数。所以,

    int n = 10;
    int arr[n] ; //incorrect
    

    正确的方法是:

    const int n = 10;
    int arr[n]; //correct
    

    您可以通过以下方式解决您的问题:

    const int n = 10;
    int arr[n] = {0}; //correct now because n is a constant expression
    

    更多示例:

    void func(int n)
    {
       int arr[n] = {0}; //incorrect because n is passed as a function argument and is therefore not a compile time constant
    }
    

    另一个例子

    int n;
    cin >> n;
    int arr[n] = {0}; //incorrect
    

    您可以使用std::vector,因为它是一个动态大小的容器。

    【讨论】:

    • 但是如果您在类中的函数中获取数组大小作为参数怎么办?
    • const int r = n+1; int dp[r] = {0};
    • @DeepakSilver 单击我的答案中的VLA:s 链接以阅读相关内容。
    • @DeepakSilver 如果将int 作为参数传递给函数,则不能使用该参数来指定数组的大小。我在答案的末尾添加了一个示例。看看吧。
    【解决方案2】:

    初始化 c++ 数组有哪些不同的方法?

    他们是:

    • 默认初始化(这意味着在琐碎对象的情况下“不初始化”)
    • 列表初始化
    • 值初始化(使用空列表进行列表初始化)

    为什么会出现这个错误?

    您的程序格式不正确。数组变量的大小必须是编译时常量,但n+1不是。

    您正在使用语言扩展。正如错误消息所暗示的那样,语言扩展不允许使用所有形式的初始化。您可以像在第一个代码示例中那样使用默认初始化,即“否”初始化。

    但是,如果您在类中的函数中将数组大小作为参数获取呢?

    然后创建一个动态数组。我推荐使用std::vector。

    【讨论】:

      【解决方案3】:

      初始化 c++ 数组有哪些不同的方法?

      这里有描述:Aggregate initialization。

      主要问题是标准 C++ 中不存在 VLA:s(可变长度数组),因此您应该使用 std::vector&lt;int&gt; dp(n+1); 而不是 int dp[n+1];

      例子:

      #include <algorithm>
      #include <climits>
      #include <cmath>
      #include <vector>
      
      class Solution {
      public:
          int numSquares(int n) {
              std::vector<int> dp(n + 1);       // instead of `int dp[n+1];`
              // for(int i=0;i<=n;i++) dp[i]=0; // no need
      
              for(int i =  1; i <= n; i++) {
                  int t = INT_MAX;
                  for(int j = 1, end = (int) std::sqrt(i); j <= end; ++j) {
                      t = std::min(t, dp[i - j * j]);
                  }
                  dp[i] = t + 1;
              }
              return dp[n];
          }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-19
        • 1970-01-01
        • 1970-01-01
        • 2020-02-26
        • 2021-08-03
        • 1970-01-01
        • 2020-04-17
        相关资源
        最近更新 更多