C ++在程序运行时声明数组 [英] C++ declaring array while the program is running

查看:65
本文介绍了C ++在程序运行时声明数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在程序运行时声明数组?

类似于:



给std :: cin>>我
int array [l];





它不起作用,它得到了一个Intelisence Err,



表达式必须有一个实例值。



我正在使用visual studio 2010.



谢谢,

解决方案

使用new和delete的另一种方法是使用STL(标准模板库)向量类 - 然后你不必担心解除分配,因为vector类处理它。

例如

  #include   <   vector  >  

void foo()
{
std :: cin>> LEN;
std :: vector< int>一个(LEN);
// 使用数组a...
}







问候,

Ian。


< blockquote>类似的东西:



  void  foo()
{
std :: cin>> LEN;
int * a = new int [长度]; // array是VC ++中的保留关键字,因为它在C ++ / CLI中使用。
// 使用数组a...
delete [] a;使用new []分配后, // 必须使用delete [] - 方括号很重要。
}


How can i declare an array while the program is running?
Something like :

std::cin>> l ;
int array[l] ;



It doesn''t work, it gets an Intelisence Err,

Expression must have an instance value.

I''m using visual studio 2010.

Thank you,

解决方案

An alternative to using new and delete is to use the STL (standard template library) vector class - then you don''t need to worry about deallocating since the vector class handles it.
E.g.

#include <vector>

void foo()
{
    std::cin >> len;
    std::vector<int> a(len);
    // use the array "a"...
}




Regards,
Ian.


Something like this:

void foo()
{
    std::cin >> len;
    int* a = new int[len];  // "array" is a reserved keyword in VC++ as it is used in C++/CLI.
    // use the array "a"...
    delete [] a;  // after allocating with new[] you must use delete[] - the square brackets are important.
}


这篇关于C ++在程序运行时声明数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆