我想用用户定义的大小初始化一个数组,但我知道的是 - 我必须声明一个最大大小的数组,然后在这个过程中处理用户给定的元素数量巨大的内存浪费。有什么方法可以声明用户给定大小的数组。 我这样做了,但编译器显示错误。
int a=0;
std::cout<<"Enter size of array";
std::cin>>a;
const int b=a;
int ary[b];
我正在使用 Turbo C++IDE
最佳答案
您的代码存在的问题是您声明了所谓的可变长度数组,它不是 C++ 的一部分(尽管它是有效的 C 代码)。参见 this解释原因。
不过,您可以通过几种不同的方式实现您想要做的事情:
您可以使用用户提供的大小动态分配数组:
#include <iostream>
#include <memory>
int main(int argc, char** argv)
{
std::size_t a =0;
std::cout<<"Enter size of array";
std::cin>>a;
std::unique_ptr<int[]> arr(new int[a]);
//do something with arr
//the unique ptr will delete the memory when it goes out of scope
}
这种方法可行,但可能并不总是理想的,尤其是在数组大小可能需要频繁更改的情况下。在那种情况下,我建议使用 std::vector
:
#include <iostream>
#include <vector>
int main(int argc, char** argv)
{
std::size_t a =0;
std::cout<<"Enter size of array";
std::cin>>a;
std::vector<int> arr(a);//arr will have a starting size of a
//use arr for something
//all of the memory is managed internally by the vector
}
您可以找到引用页 here .
关于c++ - 用户定义的数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42592628/