How to use the same iterator twice, once for counting and once for iteration?

后端 未结 3 1146
悲哀的现实
悲哀的现实 2021-01-12 07:47

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

3条回答
  •  礼貌的吻别
    2021-01-12 08:17

    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 Iterators 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 cloned. 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.

提交回复
热议问题