繁体   English   中英

用户定义的数组大小

[英]User defined size of array

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

int a=0;
std::cout<<"Enter size of array";
std::cin>>a;
const int b=a;
int ary[b];

我正在使用Turbo C ++ IDE

代码的问题在于,您正在声明不属于C ++的可变长度数组(尽管它是有效的C代码)。 请参阅说明原因。

但是,您可以通过几种不同的方式来实现您想要做的事情:

您可以使用用户提供的大小动态分配数组:

#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
}

您可以在此处找到参考页。

您可以在声明动态数组时使用new关键字

int main()
{
  int array_size;

  std::cin >> array_size;

  int *my_array = new int[array_size];

  delete [] my_array;

  return 0;
}

您应该删除分配给new的数组。

您还可以使用向量在c ++中动态分配内存。 在此处阅读有关矢量的示例

暂无
暂无

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

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