Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用模板函数从CSV文件中读取数字_C++_Templates - Fatal编程技术网

C++ 使用模板函数从CSV文件中读取数字

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;

我想知道是否有一种优雅的方法可以编写一个函数,使用模板函数将数字列表(int或double)读入向量

以下是我通常做的:

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建议的方法。