for associative arrays we can write
对于关联数组,我们可以编写
if( elem in array) { .. }
what do we write for a simple array? I want to write validation e.g.
对于一个简单的数组我们要写什么?我想写确认信。
enforce(input in [10,20,40]);
2 个解决方案
#1
17
in
sadly doesn't work on array. You must use canFind
or search
defined in std.algorithm
http://dlang.org/phobos/std_algorithm.html. Since you only want to know if it's present, not where it is, canFind
is the right tool.
不幸的是,在数组上不起作用。您必须使用std.algorithm http://dlang.org/phobos/std_algorithm.html中定义的canFind或搜索。因为你只想知道它是否存在,而不是它在哪里,所以canFind是正确的工具。
import std.algorithm: canFind;
if (my_array.canFind(42)) { stuff }
#2
4
In addition to canFind, there is also countUntil which will get you the index of the first occurrence.
除了canFind之外,还有countUntil它将为您获取第一个事件的索引。
Note that D's "in" keyword searches the associative array's keys and not its values :
注意,D的“in”关键字搜索关联数组的键,而不是它的值:
string[string] array = [
"foo" : "bar"
];
writeln(("foo" in array) != null); // true
writeln(("bar" in array) != null); // false
#1
17
in
sadly doesn't work on array. You must use canFind
or search
defined in std.algorithm
http://dlang.org/phobos/std_algorithm.html. Since you only want to know if it's present, not where it is, canFind
is the right tool.
不幸的是,在数组上不起作用。您必须使用std.algorithm http://dlang.org/phobos/std_algorithm.html中定义的canFind或搜索。因为你只想知道它是否存在,而不是它在哪里,所以canFind是正确的工具。
import std.algorithm: canFind;
if (my_array.canFind(42)) { stuff }
#2
4
In addition to canFind, there is also countUntil which will get you the index of the first occurrence.
除了canFind之外,还有countUntil它将为您获取第一个事件的索引。
Note that D's "in" keyword searches the associative array's keys and not its values :
注意,D的“in”关键字搜索关联数组的键,而不是它的值:
string[string] array = [
"foo" : "bar"
];
writeln(("foo" in array) != null); // true
writeln(("bar" in array) != null); // false