数组+ C ++中的常量表达式 [英] array + constant expression in c++

查看:87
本文介绍了数组+ C ++中的常量表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户那里获取n并将其放在数组表达式上,但是在Visual Studio 2017中却遇到了一个错误(表达式必须具有恒定值),我看到其他编译器可以完美地工作.我以为我可以使用new或指针,但是那些也不起作用.我知道也有类似的主题(我听不懂它们并不能将它们与我的问题相匹配),但是如果有人为我编写正确的代码,那就太好了.谢谢.

I want to get n from the user and put it on array expression but in visual studio 2017 a getting error ( expression must have a constant value ), I saw other compilers work with that perfectly. I thought I could use new or a pointer but those don't work too. I know there is similar topic for it (i couldn't understand them and match them with my problem ) but it would be great if someone writes correct code for me. thanks.

  int n;
    cout <<"Enter n:" ;
    cin >> n;
    int a[n];    //recive error for n (expression must have a constant value)

    for(int i=0;i<n;i++)
         a[i]=rand() % 100;

    for(int i=0;i<n;i++)        
        cout<<setw(5)<< a[i];

推荐答案

在C ++中,数组必须具有固定的大小.您不能有一个其大小取决于运行时值的普通数组.这就是为什么编译器会抱怨 n int a [n]; .

In C++, arrays must have fixed sizes. You can not have a plain array whose size depends on a run-time value. This is why the compiler complains that n is not constant in int a[n];.

您应该使用 std :: vector 代替: std :: vector< int>a(n); 将创建一个可以容纳 n 个元素的向量.您的其余代码可以保持不变.

You should use std::vector instead: std::vector<int> a(n); will create a vector that can hold n elements. The rest of your code can stay the same.

这篇关于数组+ C ++中的常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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