将一系列范围传递给可变参数函数

发布于 2024-11-13 07:03:12 字数 738 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羅雙樹 2024-11-20 07:03:12

如果您不知道 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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文