检查一个值是否存在于(未排序的)数组中
Check if a value is present in an (unsorted) array
在 D 语言中 in
运算符允许检查一个值是否存在于已排序的随机访问范围中。
但是如果我想检查某个值是否存在于未排序且非随机访问范围内,该怎么做?
使用std.algorithm.searching : countUntil
import std.algorithm.searching : countUntil
if (array.countUntil(lookingFor) != -1) {
// . . .
}
count Until
类似于许多其他语言中的 indexOf。
https://dlang.org/phobos/std_algorithm_searching.html#countUntil
虽然我同意 Lupus 的观点,countUntil
可以完成这项工作,但还有一个不同的函数可能开销更少,名称更合理:canFind
:
import std.algorithm.searching : canFind;
if (haystack.canFind(needle)) {
// ...
}
在 D 语言中 in
运算符允许检查一个值是否存在于已排序的随机访问范围中。
但是如果我想检查某个值是否存在于未排序且非随机访问范围内,该怎么做?
使用std.algorithm.searching : countUntil
import std.algorithm.searching : countUntil
if (array.countUntil(lookingFor) != -1) {
// . . .
}
count Until
类似于许多其他语言中的 indexOf。
https://dlang.org/phobos/std_algorithm_searching.html#countUntil
虽然我同意 Lupus 的观点,countUntil
可以完成这项工作,但还有一个不同的函数可能开销更少,名称更合理:canFind
:
import std.algorithm.searching : canFind;
if (haystack.canFind(needle)) {
// ...
}