将一系列范围传递给可变参数函数
Phobos 文档显示了传递给可变参数函数的范围的以下示例
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7][]));
assert(equal(setIntersection(a, b, c), [1, 4, 7][]));
但是,如果您有一个范围范围,并且您事先不知道它将包含多少个元素,就像
int[][] a = [[1,2,3,4],[1,2,4,5],[1,3,4,5]];
我唯一能想到的是
if (a.length > 1) {
auto res = array(setIntersection(a[0], a[1]));
for (int i = 2; i < a.length; i++)
res = array(setIntersection(res, a[i]));
writeln(res);
}
哪个有效。但我希望能够将参数直接传递给函数,例如 setIntersection(a.tupleof) 或类似的东西(我知道 tupleof 在这里不起作用)。
The Phobos documentation shows the following example of ranges passed to a variadic function
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7][]));
assert(equal(setIntersection(a, b, c), [1, 4, 7][]));
But what if you have a range of ranges, and you don't know in advance how many elements it will contain, like
int[][] a = [[1,2,3,4],[1,2,4,5],[1,3,4,5]];
The only thing I can think of is
if (a.length > 1) {
auto res = array(setIntersection(a[0], a[1]));
for (int i = 2; i < a.length; i++)
res = array(setIntersection(res, a[i]));
writeln(res);
}
Which works. But I was hoping to be able to pass the argument directly to the function, like setIntersection(a.tupleof) or something like that (I know that tupleof doesn't work here).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不知道
a
将有多少个元素,您将无法在编译时将其扩展为元组(并因此将其传递到函数中),因此 for 循环是最好的选择下注(或实现您自己的
setIntersection
,它可以采用一系列范围)if you don't know how many elements
a
will have you won't be able to expand it into a tuple at compile time (and consequently pass it into a function)so that for loop is your best bet (or implement your own
setIntersection
that can take a range of ranges)