how to skip the next (n) item & continue from (n+1) with a range ? e.g. in File(fn).byLine();

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 22 21:27:12 UTC 2020


On 6/22/20 4:49 PM, mw wrote:
> On Monday, 22 June 2020 at 20:46:30 UTC, mw wrote:
>> On Monday, 22 June 2020 at 20:00:50 UTC, Steven Schveighoffer wrote:
>>> I wouldn't recommend it, instead do a while loop:
>>>
>>> auto range = File(fn).byLine;
>>>
>>> while(!range.empty)
>>> {
>>>    auto line = range.front;
>>>    if(someCond(line)) {
>>>         range.popFrontN(n);
> 
> I'm asking this, because here it need to be range.popFrontN(n+1);

`n` actually isn't defined, you defined it in a comment in your original 
code ;) I just threw it in there. Of course, make sure it works how you 
are expecting, I don't know what your code is doing.

> 
> i.e. bug-prone
> 
> can be fixed by:
>     auto line = range.front;
>     range.popFront;  // pop immediately

This is a bad idea, once you popFront, the original front is possibly 
invalid (and technically is the case for byLine).

> 
> 
>>>    } else {
>>>         regularProcess(line);
>>>         range.popFront;
>>>    }
>>> }
>>
>> Thanks.
>>
>> so `front` is peek, and `popFront` is the pop action whose return type 
>> is `void`, why we need two *separate* calls instead of just let 
>> `popFront` return T (or do we have another function for this)? i.e if 
>> the user forget `popFront`, it will prone to infinite loop bug?
> 
> so my question.

There is no requirement to actually construct members. e.g. popFrontN 
calls popFront N times, but does not actually invoke front at all.

Separating the concerns is for correctness and performance.

-Steve


More information about the Digitalmars-d-learn mailing list