Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array contains element in D

Tags:

arrays

d

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]);
like image 903
Parobay Avatar asked Jun 02 '14 12:06

Parobay


People also ask

How do I check if an array contains a value?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.


2 Answers

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.

import std.algorithm: canFind;

if (my_array.canFind(42)) { stuff }
like image 185
Nil Avatar answered Oct 16 '22 05:10

Nil


In addition to canFind, there is also countUntil which will get you the index of the first occurrence.

Note that D's "in" keyword searches the associative array's keys and not its values :

string[string] array = [
    "foo" : "bar"
];

writeln(("foo" in array) != null); // true
writeln(("bar" in array) != null); // false
like image 41
Hassan Avatar answered Oct 16 '22 07:10

Hassan