我正在写一个.csv导入器,它接收一个文件名并输出一个2d数组。
template<size_t ROW,size_t COL>
Matrix<double, ROW, COL > importcsv(string filename){
ifstream myfile (filename); //Constructs a stream, and then asssociates the stream with the file "filename"
vector<double> contentsasvector; // Vector which will store the contents of the stream.
int i=1; int j=1;
while(!myfile.eof()){
if(myfile.get()==','){++j;}
else if(myfile.get()=='\n'){++i;}
else{contentsasvector.push_back(myfile.get());}
}
myfile.close(); // Closes the filestream "my file"
constexpr int rows=i;
constexpr int cols=j/i;
Matrix<double, rows, cols> contents; // Array which will become a 2d version of the vector.
for (int k = 0; k < rows; ++k){
for (int l = 0; l < cols; ++l){
contents[k][l]=contentsasvector[k*(j/i)+l];
}
}
return contents;
}
令我感到困惑的是,我收到以下错误消息,即使我将行和列声明为constexpr。反正有吗?
error: non-type template argument is not a constant expression
Matrix<double, rows, cols> contents; // Array which will become a 2d version of the vector.
^~~~
答案 0 :(得分:0)
您正在为行分配非常量值,这意味着它的值在编译时是未知的,因此您不能将其用作模板参数。编译器应该告诉你这个。如果您要在运行时选择行号和列号,我不确定模板是否是最好的选择。