C ++预期不断前pression [英] C++ expected constant expression
问题描述
的#include<&iostream的GT;
#包括LT&;&的fstream GT;
#包括LT&;&CMATH GT;
#包括LT&;&math.h中GT;
#包括LT&;&了iomanip GT;
使用std :: ifstream的;
使用命名空间std;INT主要(无效){
诠释计数= 0;
浮总和= 0;
浮动最大= -1000000;
浮sumOfX;
浮sumOfY;
INT大小;
INT negativeY = 0;
INT positiveX = 0;
INT negativeX = 0;
ifstream的点; //点从文件导入
//points.open(data.dat文件);
//点>>大小;
// COUT<<尺寸和LT;< ENDL;大小= 100;
浮动X [大小] [2];
而(COUNT<大小){点>>(X [计数] [0]);
// COUT<<X =<<(X [计数] [0])LT;<; //读取x值
点>>(X [计数] [1]);
// COUT<<Y =<<(X [计数] [1])LT;< ENDL; // y中值读取
算上++;
}
此程序是给我在哪里,我宣布浮动X [尺寸]行预期不断前pression错误[2]。为什么呢?
浮动X [大小] [2];
这不起作用,因为声明数组不能有运行时的大小。尝试载体:
的std ::矢量<的std ::阵列<浮动,2 - ; > X(大小);
或者使用新的
//身份和LT;浮动[2]> ::键入* PX =新的浮动[大小] [2];
浮动(* PX)[2] =新的浮动[大小] [2];// ...使用,然后删除
删除[]像素;
如果你没有C ++ 11可用,则可以使用的boost ::阵列
而不是的std ::阵列
。
如果你没有可用的提升,使自己的数组类型你能坚持到载体
模板< typename的T,为size_t N'GT;
结构数组{
数据T [N];
T&放大器;运营商[](ptrdiff_t的我){返回数据[I] }
ŧ常量和放大器;运营商[](ptrdiff_t的我)const的{返回数据[I] }
};
有关缓解新
,您可以使用身份
模板语法这是一个有效的就地的typedef (在升压也可
)
模板< typename的T>
结构身份{
typedef的T形;
};
如果你愿意,你也可以使用性病的矢量::对<浮球,浮球>
的std ::矢量<性病::对<浮球,浮球GT; > X(大小);
//语法:X [I]。首先,X [I]。第二
#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++;
}
This program is giving me expected constant expression error on the line where I declare float x[size][2]. Why?
float x[size][2];
That doesn't work because declared arrays can't have runtime sizes. Try a vector:
std::vector< std::array<float, 2> > x(size);
Or use new
// identity<float[2]>::type *px = new float[size][2];
float (*px)[2] = new float[size][2];
// ... use and then delete
delete[] px;
If you don't have C++11 available, you can use boost::array
instead of std::array
.
If you don't have boost available, make your own array type you can stick into vector
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]; }
};
For easing the syntax of new
, you can use an identity
template which effectively is an in-place typedef (also available in boost
)
template<typename T>
struct identity {
typedef T type;
};
If you want, you can also use a vector of std::pair<float, float>
std::vector< std::pair<float, float> > x(size);
// syntax: x[i].first, x[i].second
这篇关于C ++预期不断前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!