初始化c++数组的所有不同方法是什么

what are all the different ways to initialize a c++ array?

本文关键字:方法 是什么 c++ 数组 初始化      更新时间:2024-04-27
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++中,数组的大小必须是编译时常数。所以,

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,因为它是动态大小的容器

初始化c++数组的所有不同方法是什么?

它们是:

  • 默认初始化(对于琐碎的对象,这意味着"不初始化"(
  • 列表初始化
  • 值初始化(即使用空列表进行列表初始化(

为什么会出现此错误?。

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

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

但如果您在类中的函数中获取数组大小作为参数,该怎么办?

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

初始化c++数组的所有不同方法是什么?

此处介绍:聚合初始化。

主要问题是VLA:s(可变长度数组(在标准C++中不存在,因此应该使用int dp[n+1];而不是std::vector<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];
}
};