It seems that an iterator is consumed when counting. How can I use the same iterator for counting and then iterate on it?
I\'m trying to count the lines in a file an
Iterators can generally not be iterated twice because there might be a cost to their iteration. In the case of str::lines
, each iteration needs to find the next end of line, which means scanning through the string, which has some cost. You could argue that the iterator could save those positions for later reuse, but the cost of storing them would be even bigger.
Some Iterator
s are even more expensive to iterate, so you really don't want to do it twice.
Many iterators can be recreated easily (here calling str::lines
a second time) or be clone
d. Whichever way you recreate an iterator, the two iterators are generally completely independent, so iterating will mean you'll pay the price twice.
In your specific case, it is probably fine to just iterate the string twice as strings that fit in memory shouldn't be so long that merely counting lines would be a very expensive operation. If you believe this is the case, first benchmark it, second, write your own algorithm as Lines::count
is probably not optimized as much as it could since the primary goal of Lines
is to iterate lines.