检查数组 D 中是否存在索引
Check If Index Exists in Array D
如果有什么不够清楚,我提前道歉。
在尝试检查 D 中数组的索引值是否存在时,我遇到了意外的 RangeError。
我正在尝试创建一个数组检查函数,但我不知道如何检查 D 中数组中的值。
在 C 中,我会使用 arr[index]
.
执行错误:
core.exception.RangeError@test.d(6): Range violation
----------------
??:? _d_arrayboundsp [0x100f855d9]
??:? int checkArray(immutable(char)[][]) [0x100f6715e]
??:? _Dmain [0x100f7832e]
代码:
import std.stdio;
import std.stdc.stdlib;
import core.sys.posix.unistd;
int checkArray(string[] arr) {
if (!arr[1]) {
return 0;
} else {
return 1;
}
}
void main() {
string base = "test";
string[] cut = base.split(" ");
checkArray(cut);
}
我目前用的是Mac,用DMD编译源码
除了 arr[index]
,我是否应该尝试其他检查器?
首先,永远不要通过取消引用来检查索引是否在数组中。
bool check(int[] arr, size_t index)
{
return index < arr.length;
}
unittest {
assert(!check([], 0));
assert(!check([1], 1));
assert(check([1, 2], 1));
auto testArray = new int[1024];
//testArray[testArray.length] = 1; // this throws, so check should return false
assert(!check(testArray, testArray.length));
}
享受
如果有什么不够清楚,我提前道歉。
在尝试检查 D 中数组的索引值是否存在时,我遇到了意外的 RangeError。
我正在尝试创建一个数组检查函数,但我不知道如何检查 D 中数组中的值。
在 C 中,我会使用 arr[index]
.
执行错误:
core.exception.RangeError@test.d(6): Range violation
----------------
??:? _d_arrayboundsp [0x100f855d9]
??:? int checkArray(immutable(char)[][]) [0x100f6715e]
??:? _Dmain [0x100f7832e]
代码:
import std.stdio;
import std.stdc.stdlib;
import core.sys.posix.unistd;
int checkArray(string[] arr) {
if (!arr[1]) {
return 0;
} else {
return 1;
}
}
void main() {
string base = "test";
string[] cut = base.split(" ");
checkArray(cut);
}
我目前用的是Mac,用DMD编译源码
除了 arr[index]
,我是否应该尝试其他检查器?
首先,永远不要通过取消引用来检查索引是否在数组中。
bool check(int[] arr, size_t index)
{
return index < arr.length;
}
unittest {
assert(!check([], 0));
assert(!check([1], 1));
assert(check([1, 2], 1));
auto testArray = new int[1024];
//testArray[testArray.length] = 1; // this throws, so check should return false
assert(!check(testArray, testArray.length));
}
享受