C++ 期望的常量表达式

2024-04-24

#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.

如果您没有可用的 boost,请创建自己的数组类型,您可以将其插入向量

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 期望的常量表达式 的相关文章

随机推荐