Dlang:foreach循环或“每个”模板

问题描述 投票:0回答:2

假设我有一个可迭代的对象数组,我想循环遍历每个对象并执行一些任务或任务。我看到了两种方法,如下所示。我有时间使用MonoTime,就执行时间而言,它们似乎具有可比性。

建议在D中使用以下哪个选项?在什么情况下推荐的选项可能没用?

    int[] animals = [animal1, animal2, animal3];

    // OPTION 1

    foreach(Animal a; animals) {
        a.feed();
        a.giveWater();
    }

    // OPTION 2
    animals.each!( (a) {a.feed();
                        a.giveWater();
                        });
d
2个回答
2
投票

foreach是默认值。

我使用each的一件事是将大量变换应用于集合(使用std.algorithm),然后迭代结果。这仅用于阅读。考虑是否要迭代以下内容:

students
    .filter!(s => s.year == 1)
    .map!(s => s.major)
    .filter!(m => m !is null)
    .map!(x => faculty.byProgram(x))
    .joiner
    .array
    .sort
    .uniq

把它放在foreach中会很尴尬。坚持使用.each!(x => writeln(x.name))是很自然的。


0
投票

我正在使用each直接调用函数。

例如:

[1, 2, 3].each!writeln();
© www.soinside.com 2019 - 2024. All rights reserved.