Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
std.algorithm.filter!()有两个参数而不是一个参数的模板?_D_Dmd - Fatal编程技术网

std.algorithm.filter!()有两个参数而不是一个参数的模板?

std.algorithm.filter!()有两个参数而不是一个参数的模板?,d,dmd,D,Dmd,以下是一个例子: int[] arr = [ 1, 2, 3, 4, 5 ]; auto foo = filter!("a < 3")(arr); assert(foo == [ 1, 2 ]); // works fine int[]arr=[1,2,3,4,5]; 自动foo=过滤器!(“a

以下是一个例子:

int[] arr = [ 1, 2, 3, 4, 5 ];
auto foo = filter!("a < 3")(arr);
assert(foo == [ 1, 2 ]); // works fine
int[]arr=[1,2,3,4,5];
自动foo=过滤器!(“a<3”)(arr);
断言(foo==[1,2]);//很好
现在我想能够参数化谓词,例如

int max = 3;
int[] arr = [ 1, 2, 3, 4, 5 ];
auto foo = filter!("a < max")(arr); // doesn't compile
int max=3;
int[]arr=[1,2,3,4,5];
自动foo=过滤器!(“a

显然,这个代码段不会编译,因为过滤器!()的谓词只接受一个参数。有没有一种方法可以克服这个限制,而不必求助于良好的ol'for/foreach循环

字符串lambda只是一种库级的便利,为了方便起见,它的设计甚至比D的内置函数/委托/模板文本还要简洁。以下是当您需要更大功率时应采取的措施:

注意:以下应该可以工作,但在编写时可能由于编译器错误而表现不稳定

import std.algorithm;

void main() {
    int max = 3;
    int[] arr = [ 1, 2, 3, 4, 5 ];
    auto foo = filter!((a) { return a < max; })(arr);
}
导入标准算法;
void main(){
int max=3;
int[]arr=[1,2,3,4,5];
自动foo=filter!((a){返回a
以下几点确实有效:

import std.algorithm;

void main() {
    int max = 3;
    int[] arr = [ 1, 2, 3, 4, 5 ];
    auto foo = filter!((int a) { return a < max; })(arr); 
}
导入标准算法;
void main(){
int max=3;
int[]arr=[1,2,3,4,5];
自动foo=filter!((inta){返回a

区别在于是否明确指定了类型。

除了dsimcha的答案外,如果愿意,还可以使用本地函数:

int max = 3;
bool pred(int a) { return a < max; };
int[] arr = [1, 2, 3, 4, 5];
auto foo = filter!(pred)(arr);
int max=3;
boolpred(inta){返回a
我会编辑你的帖子,但仍在处理代表。你应该修改第二个例子的评论。@he_the__伟大:实际上两者都可以编译。那条评论是我从OP上复制/粘贴的,却忘了删除那条评论。不过现在修好了。