从逗号分隔的文本文件中创建有意义的数据向量的最佳方法是什么?
What is the best way to create a vector of meaningful data out of a comma delimited text file
考虑以下内容:
我已经定义了一个类:
class Human
{
public:
std::string Name;
std::string Age;
std::string Weight;
}
我有一个。txt文件定义:
Justin,22,170
Jack,99,210
Fred,12,95
etc...
目标是将此文本文件转换为std::vector
我现在的代码如下:
vector<Human> vh;
std::ifstream fin(path);
std::string line;
while(std::getline(fin,line))
{
std::stringstream linestream(line);
std::string value;
Human h;
int IntSwitch = 0;
while(getline(linestream,value,','))
{
++IntSwitch;
try{
switch(IntSwitch)
{
case 1 :
h.Name = value;
break;
case 2:
h.Age = value;
break;
case 3:
h.Weight = value;
vh.push_back(h);
break;
}
}
catch(std::exception ex)
{
std::cout << ex.what() << std::endl;
}
}
}
现在我只是好奇是否有任何c++11技术或非c++11技术,将更有效/更容易阅读,然后这个?
我写了一个骨架版本,它应该与行基结构一起工作:
struct Human
{
Human(const std::string& name, const std::string& age, const std::string& weight)
: name_(name), age_(age), weight_(weight) { }
std::string name_;
std::string age_;
std::string weight_;
};
class CSVParser
{
public:
CSVParser(const std::string& file_name, std::vector<Human>& human) : file_name_(file_name)
{
std::ifstream fs(file_name.c_str());
std::string line;
while(std::getline(fs, line))
{
human.push_back(ConstructHuman(line));
}
}
Human ConstructHuman(const std::string& line);
private:
std::string file_name_;
};
Human CSVParser::ConstructHuman(const std::string& line)
{
std::vector<std::string> words;
std::string word;
std::stringstream ss(line);
while(std::getline(ss, word, ','))
{
words.push_back(word);
}
return Human(words[0], words[1], words[2]);
}
int main()
{
std::vector<Human> human;
CSVParser cp("./word.txt", human);
return 0;
}
相关文章:
- 用于筛子的最佳数据结构是什么(即一些被划掉的数字列表)?
- 用于存储分组关系和支持外观的最佳数据结构
- 适用于频繁更改的大型数据集的最佳数据结构
- 点遍历的最佳数据结构
- 代表软件包安装和系统依赖关系的最佳数据结构
- 数字序列的最佳数据结构 [0:9]
- 什么是在C 中存储结果INT*的最佳数据类型
- 用于在具有更新查询的二维矩阵中查找最大值的最佳数据结构
- 哪种数据结构是在一个向量中搜索和计数对象对的最佳数据结构
- 最佳数据结构存储文本文件中的数字集
- 用于随机访问和元素循环的最佳数据结构(C++)
- 可用于存储和管理整数集合的最佳C++数据结构是什么
- 使用C 中的单元格 /图块 /网格进行碰撞检测的最佳数据结构
- A*开放集的最佳数据结构是什么
- C++中用于插入和删除的最佳数据结构/容器
- 什么是支持优先级、更新、推送和弹出的最佳数据结构
- 从中间删除元素的最佳数据结构是什么
- 排序列表的最佳数据结构(性能)
- 寻找适合工作的最佳数据结构
- 压缩2D曲线的最佳数据结构/算法是什么?