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

该程序使我在我声明float x [size] [2]的线上预期的是恒定的表达错误。为什么?

有帮助吗?

解决方案

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 模板有效地是现场打字(也可在 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

其他提示

阵列将在编译时分配 size 不是常数,编译器无法准确确定其值。

您不能在C ++中具有可变长度阵列(在C99中称为它们)。您需要使用动态分配的数组(如果大小变化)或大小的静态积分常数表达式。

线 float x[size][2] 不起作用,因为必须在编译时分配数组(还有一些编译器特定的例外)。如果您想能够轻松更改数组的大小 x编译 时间,您可以做到这一点:

 #define SIZE 100
 float x[SIZE][2];

如果您真的想根据仅在运行时获得的信息分配数组,则需要动态分配数组 malloc 或者 new.

这是对语言的限制。阵列大小必须是恒定表达式。这是cplusplus.com的部分jsutification

注意:括号内的元素字段[]表示数组要保留的元素数,必须是恒定值,因为数组是非动态内存的块,必须在执行前确定其大小。为了创建具有可变长度的动态内存的数组,这将在这些教程后面进行解释。

自动阵列的大小必须是编译时常数。

 const int size = 100;
 float x[size][2];

如果在编译时不知道大小(例如用户输入的,从文件的内容确定),则需要使用动态分配,例如:

std::vector<std::pair<float, float> > x(somesize);

(而不是一对,而是专门的点结构/班级将是完全合理的。)

因为它期望不断表达!

C中的数组尺寸(忽略C99的VLA)和C ++必须在编译时已知。这并不意味着仅标记 const: : 他们 将其硬编码为程序。

使用动态分配或 std::vector (这是围绕动态数组分配的包装器),以确定运行时的数组大小。

您没有为大小分配任何价值;因此,编译器不能为数组分配内存。 (一个空尺寸的数组?什么?)

此外,您需要使尺寸变为恒定,而不是变量。

编辑: 不幸的是,由于海报已经改变了他们的问题,因此这种回答不再有意义。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top