. 1 2 4 0 2 0 1 0 在 C++/C++11 中最简洁的方法是什么? 这是一个蹩脚的尝试,它对空行不起作用..-6ren">
gpt4 book ai didi

C++从文件加载 "irregular"数据的最简单方法

转载 作者:行者123 更新时间:2023-11-28 00:14:05 24 4
gpt4 key购买 nike

我有一个数据文件(表示邻接表),我想将其加载为 std::vector< std::list<int> > .

1 2 4
0 2
0 1

0

在 C++/C++11 中最简洁的方法是什么?


这是一个蹩脚的尝试,它对空行不起作用......

vector< list<int> > data;
ifstream file("data.dat");
char foo;

while(file >> foo){
file.unget();
list<int> mylist;
while( file.get() != '\n'){
file.unget();
int n;
file >> n;
mylist.push_back(n);
cout << n;
}
data.push_back(mylist);
}

file.close();

最佳答案

只需逐行读取并将其解析为列表:

for (std::string line; std::getline(file, line);) {
std::istringstream str(line);
data.emplace_back(std::istream_iterator<int>(str), std::istream_iterator<int>{});
}

关于C++从文件加载 "irregular"数据的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31441110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com