2017-08-08 80 views
0

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

我的問題是與stoistod一部分。如何在這裏很好地處理這個問題?

我最常做的,就是用stod,讓若VecTypeint例如轉換從double自動發生int。但是應該有更好的方法來做到這一點,對吧?

+0

順便說一句,我會很感激的,從一排,而不是'stringstream'閱讀'cells'一個更好的方法是緩慢 – NULL

+1

如何關於'VecType e; cellStream >> e; vec.push_back(e);'? – Jarod42

回答

3

你可以有專門的模板:

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); } 

,並使用vec.push_back(from_string<VecType>(cell));

+0

我得到'錯誤:template-id'from_string '在主模板聲明'和'錯誤:'雙'不是模板非類型參數的有效類型'我缺少什麼? – NULL

+0

從我的部分來看,'<>'應該是空的。 – Jarod42

+1

這也可以通過使默認特化使用'operator >>'來擴展到任何輸入流式類型。 –