问题描述
我想使用D来计算目录中文件的数量。
I would like an easy way to count the number of files in a directory using D.
据D手册,dirEntries返回一个范围,但是没有length属性。因此,我必须使用计数器来遍历结果,或者以传统数组的形式收集名称,这些数组可以找到...的长度。是否有更好的方法?
As far as I can tell from the D manual, dirEntries returns a range, but this has no length property. I therefore have to iterate through the results with a counter, or gather up the names in a traditional array which I can find the length of... Is there a better way?
auto txtFiles = dirEntries(".", "*.txt", SpanMode.shallow);
int i=0;
foreach (txtFile; txtFiles)
i++;
writeln(i, " files found..");
推荐答案
范围通常没有 length
属性,除非可以在 O(1)
中进行计算。任何不能计算其长度大于 O(n)
的范围都不会具有 length
属性,因为它效率太低。获取没有 length
属性的范围的长度的惯用方式是使用。如果范围定义了 length
,它将使用 length
;否则,它只会在范围内迭代并计算有多少元素。
Ranges generally don't have a length
property unless it can be calculated in O(1)
. Any range which can't calculate its length in better than O(n)
isn't going to have a length
property, because it's too inefficient. The idiomatic way to get the length of a range with no length
property is to use std.range.walkLength
. It uses length
if the range defines length
; otherwise, it simply iterates over the range and counts up how many elements there are.
您还可以使用,但是它用于计算与谓词匹配的元素数,默认情况下为一个谓词,它为每个元素返回 true
,效率低于 walkLength
,因为 walkLength
在元素上进行迭代时不会对元素进行任何调用,如果已定义,它将使用 length
来代替,而计数
永远不会。
You can also use std.algorithm.count
, but it's intended for counting the number of elements which match a predicate, and while it defaults to a predicate which returns true
for every element, that's less efficient than walkLength
, because walkLength
doesn't call anything on the elements as it iterates over them, and it will use length
instead if it's been defined, whereas count
never will.
这篇关于使用Dlang计数目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!