2017-08-08 84 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 >>'来扩展到任何输入流式类型。 –