C++ 使用模板函数从CSV文件中读取数字
我想知道是否有一种优雅的方法可以编写一个函数,使用模板函数将数字列表(int或double)读入向量 以下是我通常做的:C++ 使用模板函数从CSV文件中读取数字,c++,templates,C++,Templates,我想知道是否有一种优雅的方法可以编写一个函数,使用模板函数将数字列表(int或double)读入向量 以下是我通常做的: template<class VecType> vector<VecType> read_vector(const string& file){ vector<VecType> vec; ifstream indata; indata.open(file); string line;
template<class VecType>
vector<VecType> read_vector(const string& file){
vector<VecType> vec;
ifstream indata;
indata.open(file);
string line;
while (getline(indata, line)) {
stringstream lineStream(line);
string cell;
while (std::getline(lineStream, cell, ',')) {
vec.push_back(stod(cell));
}
}
indata.close();
return vec;
}
模板
矢量读取\矢量(常量字符串和文件){
向量向量机;
Iftream indata;
打开(文件);
弦线;
while(getline(indata,line)){
线状流线状流(线状);
字符串单元;
while(std::getline(lineStream,cell,,')){
向量推回(stod(细胞));
}
}
indata.close();
返回向量;
}
我的问题是stoi
或stod
部分。这里怎么处理得好
我通常做的是使用
stod
并让转换自动从double
到int
,例如VecType
是int
。但是应该有更好的方法来实现这一点,对吗?您可以使用专门的模板:
template <class T> T from_string(const std::string&);
template <> int from_string<int>(const std::string& s) { return stoi(s); }
template <> double from_string<double>(const std::string& s) { return stod(s); }
模板T来自_字符串(const std::string&);
模板int来自_string(const std::string&s){return stoi(s);}
来自_string(const std::string&s){return stod(s);}的模板双精度
并使用
vec.push_back(从_字符串(单元格))代码>您可以有专门的模板:
template <class T> T from_string(const std::string&);
template <> int from_string<int>(const std::string& s) { return stoi(s); }
template <> double from_string<double>(const std::string& s) { return stod(s); }
模板T来自_字符串(const std::string&);
模板int来自_string(const std::string&s){return stoi(s);}
来自_string(const std::string&s){return stod(s);}的模板双精度
并使用vec.push_back(从_字符串(单元格))代码>顺便说一句,我希望有更好的方法从一行中读取单元格
,而不是stringstream
,后者在VecType方面很慢;cellStream>>e;向量推回(e)代码>?顺便说一句,我希望有更好的方法从一行中读取单元格
,而不是stringstream
,后者在VecType方面很慢;cellStream>>e;向量推回(e)代码>?我在主模板声明中获得了错误:模板id“from_string”
和错误:“double”不是模板非类型参数的有效类型
我缺少什么?我的部件输入错误,
应该是空的。通过使用默认的专门化操作符>
,这也可以扩展到任何输入流类型。这确实是一种非常优雅的处理问题的方法,尤其是@DanielH所建议的。我在主模板声明中得到了错误:模板id“from_string”
和错误:“double”不是模板非类型参数的有效类型
我缺少了什么?我的部分输入错误,
应该为空。通过使用默认的专门化运算符>>
,也可以将其扩展到任何输入流类型。这确实是一种非常优雅的处理问题的方法,尤其是@DanielH建议的方法。