D 语言代码编译报错:std.array:array 和 std.algorithm:joiner 函数参数错误

代码中使用了 D 语言标准库中的 std.array:arraystd.algorithm:joiner 函数,而这两个函数的参数必须是实现了 InputRange 接口的类型。但是在代码中,reverse 函数返回的类型是 string,而 string 并没有实现 InputRange 接口,因此编译器报错。

import std.stdio;
import std.datetime;
import std.string;
import core.memory;
import std.conv:to;
import std.array:array;
import std.algorithm:reverse,joiner;

pure string reverse1(in string old) {
    string reversedStr;
    foreach (char c; old) {
        reversedStr = c ~ reversedStr;
    }
     return reversedStr;
}
string reverse2(in string old) {
    char[] oldCharArr = old.dup;
    char* str = oldCharArr.ptr;
    ulong length = old.length;
    for (ulong i = 0, j = length - 1; i < j; i++, j--)
    {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
    return fromStringz(str).idup;
}

void main() {
    auto start = Clock.currTime();

    string str = 'hello, world!';
    for (int i = 0; i < 10000000; i++) {
        //str = str.replace('o', '0').replace('l', '1').replace(',', '').replace('!', '').reverse;
        str = str.replace('o', '0').replace('l', '1').replace(',', '').replace('!', '').array.reverse.joiner('');
        //str = str.replace('o', '0').replace('l', '1').replace(',', '').replace('!', '');
    }

    auto end = Clock.currTime();
    writeln('D语言程序运行时间:', end-start);
}

提示:

/home/chenfa/dev_soft/dmd_all/usr/include/dmd/phobos/std/algorithm/iteration.d(2975): Error: static assert: The ElementyType of RoR 'dchar' must be an InputRange (isInputRange!(ElementType!(dchar[]))). fanzhuan.d(35): instantiated from here: joiner!(dchar[], string)`

解决方法:

reverse 函数的返回值转换成实现了 InputRange 接口的类型,例如使用 array 函数将 string 转换成 char[],然后再调用 reverse 函数,最后使用 joiner 函数将结果转换成 string 类型。

正确的代码应该是这样的:

import std.stdio;
import std.datetime;
import std.string;
import core.memory;
import std.conv:to;
import std.array:array;
import std.algorithm:reverse, joiner;

pure string reverse1(in string old) {
    string reversedStr;
    foreach (char c; old) {
        reversedStr = c ~ reversedStr;
    }
    return reversedStr;
}

string reverse2(in string old) {
    char[] oldCharArr = old.dup;
    char* str = oldCharArr.ptr;
    ulong length = old.length;
    for (ulong i = 0, j = length - 1; i < j; i++, j--)
    {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
    return fromStringz(str).idup;
}

void main() {
    auto start = Clock.currTime();

    string str = 'hello, world!';
    for (int i = 0; i < 10000000; i++) {
        str = str.replace('o', '0').replace('l', '1').replace(',', '').replace('!', '');
        str = str.array.reverse.joiner('');
    }

    auto end = Clock.currTime();
    writeln('D语言程序运行时间:', end - start);
}
D 语言代码编译报错:std.array:array 和 std.algorithm:joiner 函数参数错误

原文地址: https://www.cveoy.top/t/topic/ofuy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录