c++ - 用户定义的数组大小

标签 c++ arrays

我想用用户定义的大小初始化一个数组,但我知道的是 - 我必须声明一个最大大小的数组,然后在这个过程中处理用户给定的元素数量巨大的内存浪费。有什么方法可以声明用户给定大小的数组。 我这样做了,但编译器显示错误。

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/

相关文章:

c++ - C++类的大小是如何确定的?

c++ - fstream 系列的实现是否因平台而异?

c++ - 使用 sscanf 解析字符串好吗

c++ - 矩形不在检测到的眼睛对周围

arrays - 在 Ruby 中,如何在给定要分解字符串的索引数组的情况下分解字符串?

c++ - std::move 是否会使指向 unique_ptr 所拥有的对象的原始指针无效?

javascript - 使用对象数组

ruby - 带空格的单词数组

php - PHP有peek数组操作吗?

c# - JSON 不反序列化某些值