如何在C ++中对ifstream使用两次迭代器? [英] How do I use an iterator on an ifstream twice in C++?
问题描述
我是C ++的新手,我对将迭代器与ifstream一起使用感到困惑.在下面的代码中,我有一个名为dataFile的ifstream变量.
I'm new to C++ and I'm confused about using iterators with ifstream. In this following code I have an ifstream variable called dataFile.
在代码中,我首先对文件进行一次遍历,以计算文件中有多少个字符(是否有更有效的方法?).然后,我创建一个具有该大小的矩阵,然后再次进行迭代以填充该矩阵.
In the code I first iterate through the file once to count how many characters it has (is there a more efficient way to do this?). Then I create a matrix of that size, and iterate through again to fill the matrix.
问题在于迭代器拒绝第二次迭代,并且不会做任何事情.我尝试使用dataFile.clear()从一开始就重置了ifstream,但这没有用,可能是因为我对迭代器有一些深刻的误解.有人可以帮我吗?
The problem is that the iterator refuses to iterate the second time around, and will not do anything. I tried resetting the ifstream from the beginning by using dataFile.clear(), but this didn't work, probably because I have some deep misunderstanding about iterators. Could someone help me please?
typedef istreambuf_iterator<char> dataIterator;
for (dataIterator counter(dataFile), end; counter != end; ++counter, ++numCodons) {} // Finds file size in characters.
MatrixXd YMatrix = MatrixXd::Constant(3, numCodons, 0);
dataFile.clear(); // Resets the ifstream to be used again.
for (dataIterator counter(dataFile), end; counter != end; ++counter) {...}
推荐答案
istreambuf_iterator
是一个输入迭代器,它一旦被递增,其先前值的所有副本都可能无效,而不是正向迭代器,它在用于以下情况时可以保证有效性多遍算法.有关迭代器类别的更多信息,请参见此处.
istreambuf_iterator
is an input iterator which once has been incremented, all copies of its previous value may be invalidated, not a forward iterator which guarantees validity when used in multipass algorithms. More about the category of iterators, see here.
这篇关于如何在C ++中对ifstream使用两次迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!