Parobay
Parobay

Reputation: 2619

Check if array contains element in 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]);

Upvotes: 15

Views: 5055

Answers (2)

Hassan
Hassan

Reputation: 626

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

Upvotes: 3

Nil
Nil

Reputation: 2390

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 }

Upvotes: 24

Related Questions