How to reverse char[]?
James Miller
james at aatch.net
Tue Feb 7 17:56:46 PST 2012
> On 02/08/2012 02:29 AM, H. S. Teoh wrote:
>>
>> Hi all,
>>
>> I'm trying to reverse a character array. Why doesn't the following work?
>>
>> import std.algorithm;
>> void main() {
>> char[] array = ['a', 'b', 'c'];
>> reverse(array);
>> }
>>
>> I get:
>>
>> Error: template std.algorithm.reverse(Range) if
>> (isBidirectionalRange!(Range)&& hasSwappableElements!(Range)) does not
>> match any function template declaration
>> Error: template std.algorithm.reverse(Range) if
>> (isBidirectionalRange!(Range)&& hasSwappableElements!(Range)) cannot deduce
>> template function from argument types !()(char[])
>>
>>
>> T
>>
>
> char[] is handled by Phobos as a range of dchar, ergo it does not have
> swappable elements. Apparently there is no template specialisation of
> 'reverse' that handles narrow strings, you might want to file an enhancement
> request.
That seems correct, the `reverse' function tests for
`isBidirectionalRange' and `hasSwappableElements'
The following code shows the results
import std.range;
import std.stdio;
import std.conv;
void main() {
char[] char_array = ['a','b','c'];
ubyte[] ubyte_array = ['a','b','c'];
writefln("isBidirectonalRange char_array:\t%s",
to!string(isBidirectionalRange!(typeof(char_array))));
writefln("isBidirectonalRange ubyte_array:\t%s",
to!string(isBidirectionalRange!(typeof(ubyte_array))));
writefln("hasSwappableElements char_array:\t%s",
to!string(hasSwappableElements!(typeof(char_array))));
writefln("hasSwappableElements ubyte_array:\t%s",
to!string(hasSwappableElements!(typeof(ubyte_array))));
}
The output is
isBidirectonalRange char_array: true
isBidirectonalRange ubyte_array: true
hasSwappableElements char_array: false
hasSwappableElements ubyte_array: true
So if just just need an array of bytes and the `char' semantics are
unimportant, then you can just use a ubyte instead. However Timon is
correct that there should probably be a narrow string version of
`reverse'.
James Miller
More information about the Digitalmars-d-learn
mailing list