Using arrays with functions taking ranges

monarch_dodra monarchdodra at gmail.com
Fri Dec 14 03:15:08 PST 2012


On Friday, 14 December 2012 at 10:20:38 UTC, Mu wrote:
> Thank you for your suggestion, bearophile.
> I ended up checking if the range is empty, and if it was, I'd 
> increment it as elements were added.
>
> Honestly, I much dislike this method.
> It does not feel right. The C++ version is more consistent 
> because of the iterators.

No it isn't. Iterators, like ranges, have no notion of the 
underlying container. You CANNOT modify the underlying container 
via a range or an iterator. the operation "++output.length" is 
NOT a valid range operation, and there is no equivalent in C++ 
either.

You have to use an output range, and use its "put" primitive. 
Note that currently, the definition of "isOutputRange" is a bit 
flawed. It'll answer "true" on arrays, which, arguably, are not 
output ranges. Ideally, you'd use a "true" "outputRange" or 
"sink", such as [Ref]Appender.

Appender will use your "input" _slice_ as a starting point, but 
will not actually modify your slice.
RefAppender will modify your slice.

Furthermore, note there is a bug in your code:
When you write "to!string", this will transform your 
representation into a string, NOT re-interpret into a string. It 
will LITERALLY generate the string:
"[65, 116, 116, 97, 99, 107, 32, 97, 116, 32, 111, 110, 99, 101, 
33]"

Here is your program, tweaked and with extra tests to show you 
all that together.

http://dpaste.dzfl.pl/b61fe4c5

Hope that helps. Please feel free to ask if there are more doubts.


More information about the Digitalmars-d-learn mailing list