n0o*_*0ob 7 c++ arrays constant-expression
#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++;
}
Run Code Online (Sandbox Code Playgroud)
这个程序在我声明浮动x [大小] [2]的行上给出了预期的常量表达式错误.为什么?
Joh*_*itb 12
float x[size][2];
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为声明的数组不能具有运行时大小.试试矢量:
std::vector< std::array<float, 2> > x(size);
Run Code Online (Sandbox Code Playgroud)
或者使用新的
// identity<float[2]>::type *px = new float[size][2];
float (*px)[2] = new float[size][2];
// ... use and then delete
delete[] px;
Run Code Online (Sandbox Code Playgroud)
如果您没有可用的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]; }
};
Run Code Online (Sandbox Code Playgroud)
为了简化语法new,您可以使用一个identity有效的就地typedef模板(也可用boost)
template<typename T>
struct identity {
typedef T type;
};
Run Code Online (Sandbox Code Playgroud)
如果你愿意,你也可以使用矢量 std::pair<float, float>
std::vector< std::pair<float, float> > x(size);
// syntax: x[i].first, x[i].second
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36115 次 |
| 最近记录: |