我在想如果有一種優雅的方式來編寫單個函數,它使用模板化函數將數字列表(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