我在想如果有一种优雅的方式来编写单个函数,它使用模板化函数将数字列表(int或double)读入向量中?使用模板化函数从CSV文件中读取数字
这是我平时做:
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;
}
我的问题是与stoi
或stod
一部分。如何在这里很好地处理这个问题?
我最常做的,就是用stod
,让若VecType
是int
例如转换从double
自动发生int
。但是应该有更好的方法来做到这一点,对吧?
顺便说一句,我会很感激的,从一排,而不是'stringstream'阅读'cells'一个更好的方法是缓慢 – NULL
如何关于'VecType e; cellStream >> e; vec.push_back(e);'? – Jarod42