Guido Van Rossum在article中演示了Python的简单性,并将此函数用于对未知长度的文件进行缓冲读取:
def intsfromfile(f):
while True:
a = array.array('i')
a.fromstring(f.read(4000))
if not a:
break
for x in a:
yield x
因为速度的原因,我需要在C++中做同样的事情!我有许多文件包含无符号64位整数的排序列表,我需要合并它们。我找到了一个很好的code来合并向量。在我被困在如何使一个未知长度的文件的ifstream呈现为一个向量,它可以被愉快地迭代到文件的末尾。有什么建议吗?我是否用一个istreambuf_迭代器查找正确的树?在
为了将
ifstream
(或者实际上是任何输入流)伪装成迭代器的形式,您需要使用istream_iterator
或istreambuf_iterator
模板类。前者对于需要关注格式的文件很有用。例如,可以将一个充满空格分隔整数的文件读入向量的迭代器范围构造函数,如下所示:istreambuf_iterator
用于一次读取一个字符的文件,而不考虑输入的格式。也就是说,它将返回所有字符,包括空格、换行符等。根据您的应用程序,这可能更合适。在注意:scottmeyers在effectivestl中解释了为什么上面需要为
^{pr2}$ <>但是,C++实际上以难以置信的怪异方式解析第二行。它将其视为一个名为istream_iterator
单独声明变量。通常,你会这样做:my_ints
的函数的声明,该函数接受两个参数并返回一个vector<int>
。第一个参数是istream_iterator<int>
类型,名为infile
(parathese被忽略)。第二个参数是一个没有名字的函数指针,它接受零参数(因为paratheses),并返回一个istream_iterator<int>
类型的对象。在很酷,但如果你不小心的话,也会让你很恼火。在
编辑
下面是一个使用
istreambuf_iterator
读取端到端排列的64位数字文件的示例:现在,我个人更不喜欢这种解决方案(使用
reinterpret_cast
,公开char_input
的数组),但是我对istreambuf_iterator
不太熟悉,不能轻松地使用一个超过64位字符的模板,这会使这一点变得容易得多。在相关问题 更多 >
编程相关推荐