Hey guys here's a interesting challenge for you all. I'm given a text file and I'm supposed to process the information line by line. The processing part is trivial so long as I can obtain the individual lines. However here's the challenge:
- I must do so WITHOUT using any FOR/WHILE loops in my code. (This include recursions)
- I am only allowed to use the standard C++ library.
Currently right now my best solution is this: Is there a C++ iterator that can iterate over a file line by line? but I'm hoping for a better one that does not involve creating my own iterator class or implementing a proxy for std::string.
P.S. this is for a school assignment and the challenge here was to solve the problem using a combination of std functionalities and algorithms but I have no clue how to go about solving it
Your input operator can be something like this:
There are a lot of loops here (you dont' want to use
goto
, don't you?), but they are all hidden behindstd::copy
andstd::getline
This is just a toy.
It consists of a Generator based way to slurp up files (which I find easy to write), together with a half-working adapter that turns Generators into Iterators.
A Generator in this context is a functor that takes a lambda, and passes that lambda the thing iterated over and returns true, or returns false. It makes a really short loop:
but you aren't allowed to use that. (This design is inspired by python generators, which I honestly find much more natural to work with than C++ iterators for many kinds of problem, which includes reading from a file).
The adpator takes this generator and makes it an iterator, so you can pass it to
for_each
.The point of this is that your question itself is inane, so rather than do something obvious (goto, or directly use
for_each
on an istream iterator), I'm proposing messing around with something obtuse and different. :)The Line generator is nice and short:
The adaptor, on the other hand, is pretty messy: (and not tested)
I hope this amuses!