#include <iostream>
#include <fstream>
#include <cmath>
#include <math.h>
#include <iomanip>
using std::ifstream;
using namespace std;
int main (void)
{
int count=0;
float sum=0;
float maximum=-1000000;
float sumOfX;
float sumOfY;
int size;
int negativeY=0;
int positiveX=0;
int negativeX=0;
ifstream points; //the points to be imported from file
//points.open( "data.dat");
//points>>size;
//cout<<size<<endl;
size=100;
float x[size][2];
while (count<size) {
points>>(x[count][0]);
//cout<<"x= "<<(x[count][0])<<" ";//read in x value
points>>(x[count][1]);
//cout<<"y= "<<(x[count][1])<<endl;//read in y value
count++;
}
这个程序在我声明浮动x [size] [2]的行上给出了预期的常量表达式错误。为什么呢?
答案 0 :(得分:12)
float x[size][2];
这不起作用,因为声明的数组不能具有运行时大小。尝试一个矢量:
std::vector< std::array<float, 2> > x(size);
或使用新的
// identity<float[2]>::type *px = new float[size][2];
float (*px)[2] = new float[size][2];
// ... use and then delete
delete[] px;
如果您没有可用的C ++ 11,则可以使用boost::array
代替std::array
。
如果您没有可用的增强功能,请创建您自己的阵列类型,您可以将其添加到矢量
template<typename T, size_t N>
struct array {
T data[N];
T &operator[](ptrdiff_t i) { return data[i]; }
T const &operator[](ptrdiff_t i) const { return data[i]; }
};
为了简化new
的语法,您可以使用identity
模板,该模板实际上是就地typedef(也可在boost
中使用)
template<typename T>
struct identity {
typedef T type;
};
如果需要,您还可以使用std::pair<float, float>
std::vector< std::pair<float, float> > x(size);
// syntax: x[i].first, x[i].second
答案 1 :(得分:8)
数组将在编译时分配,由于size
不是常量,编译器无法准确确定其值。
答案 2 :(得分:4)
在C ++中不能有可变长度数组(因为它们在C99中调用)。您需要使用动态分配的数组(如果大小不同)或大小的静态整数常量表达式。
答案 3 :(得分:2)
行float x[size][2]
将不起作用,因为必须在编译时分配数组(具有一些特定于编译器的异常)。如果您希望能够在编译时轻松更改数组x
的大小,可以执行以下操作:
#define SIZE 100
float x[SIZE][2];
如果您真的想根据您在运行时只拥有的信息来分配数组,则需要使用malloc
或new
动态分配数组。
答案 4 :(得分:1)
这是语言的限制。数组大小必须是常量表达式。这是来自cplusplus.com的部分jsutification
注意:括号[]中的元素字段表示数组要保存的元素数,必须是常量值,因为数组是非动态内存块,其大小必须在执行前确定。为了创建具有可变长度的数组,需要动态内存,这将在后面的教程中进行解释。
答案 5 :(得分:1)
您尚未为尺寸指定任何值;因此编译器无法为数组分配内存。 (一个null大小的数组?什么?)
此外,您需要使SIZE成为常量,而不是变量。
编辑:不幸的是,由于海报改变了他们的问题,这种反应不再有意义。
答案 6 :(得分:1)
自动数组的大小必须是编译时常量。
const int size = 100;
float x[size][2];
如果在编译时未知大小(例如由用户输入,根据文件内容确定),则需要使用动态分配,例如:
std::vector<std::pair<float, float> > x(somesize);
(而不是一对,专用的Point结构/类将非常有意义。)
答案 7 :(得分:1)
因为它期望一个恒定的表达!
C中的数组维度(忽略C99的VLA)和C ++必须是编译时已知的数量。这并不意味着只标有const
:他们将硬编码到程序中。
使用动态分配或std::vector
(动态数组分配的包装)来确定运行时的数组大小。