简体   繁体   English

如何在C++中声明一个用变量初始化的数组

[英]How to declare an array initialize with an variable in C++

I know this sound easy to you guys but I think this may be different我知道这对你们来说听起来很容易,但我认为这可能有所不同

Here is my simple code in which i am getting error in declaring Array这是我在声明 Array 时出错的简单代码

#include<iostream>
using namespace std;

int top=-1,capacity=2;
int arr[capacity];

main(){
}//main

A fixed length array needs a compile-time constant to declare its size.固定长度的数组需要一个编译时常量来声明其大小。 You need to declare capacity as const or constexpr in order to use it in an array declaration, eg:您需要将capacity声明为constconstexpr才能在数组声明中使用它,例如:

#include <iostream>
using namespace std;

int top = -1;
const int capacity = 2;
int arr[capacity];

main(){
}

If you want to define the capacity at runtime then you need to use a dynamic array, like std::vector , eg:如果要在运行时定义capacity ,则需要使用动态数组,例如std::vector ,例如:

#include <iostream>
#include <vector>
using namespace std;

int top = -1, capacity;
vector<int> arr;

main(){
    capacity = ...;
    arr.resize(capacity);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM