【发布时间】:2017-10-03 20:46:33
【问题描述】:
我有一些代码定义了一个名为“size”的变量,然后使用它,但由于某种原因它不起作用;错误是“表达式未计算为常数”
int main()
{
int size;
int userValue;
char input;
do
{
cout << "Enter an int for the size of the array:" << endl;
cin >> size;
int a[size];
cout << "Enter an integer between 1 and " << size << " to search for in the array." << endl;
cin >> userValue;
populateArray(a, size);
linearSearch(a, size, userValue);
binarySearch(a, size, userValue);
cout << "Press 'y' and enter to run again or just enter to quit";
cin.sync();
cin.get(input);
}while(input == 'y');
}
你可以忽略其他函数,因为它们在定义我的数组之前没有被调用,我尝试将大小设置为一个值,仍然不起作用。
编辑:忘了提
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
【问题讨论】:
-
int a[size]是一个可变长度数组——它不是标准 C++ 的一部分。你应该使用std::vector。 -
技术上你不能。数组大小必须在编译时知道。一些编译器提供了一个允许可变长度数组的扩展,但是一旦你设置了大小,大小就固定了。无论如何,您的编译器似乎不提供 VLA 扩展。请改用
std::vector。 -
啊,所以我必须使用 Vectors ;好的,无论如何,谢谢,我只是确保我没有其他方法可以做到这一点!
-
@Wintér 没有
std::vector有很多方法可以做到这一点,但这是最简单的解决方案。如果您拒绝使用标准库,您可以使用new[]和delete[]侥幸逃脱,但不建议这样做。 -
@FrançoisAndrieux 内存管理将花费更多时间,我现在将使用矢量,无论如何谢谢!
标签: c++