如何连接两个数组? [英] How to concatenate two arrays?

查看:162
本文介绍了如何连接两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[indent=4]

init
    x: array of int = {1, 2, 3}
    y: array of int = {4, 5, 6}
    z: array of int = x + y

以上code产生此错误消息:

The above code produces this error message:

concat_arrays.gs:6.23-6.27: error: Incompatible operand
    z: array of int = x + y

在瓦拉的翻译并不好任何工作:

The Vala translation doesn't work any better:

int main () {
    int[] x = {1, 2, 3};
    int[] y = {4, 5, 6};
    int[] z = x + y;
    return 0;
}

错误消息是:

concat_arrays_v.vala:4.15-4.19: error: Incompatible operand
    int[] z = x + y;

什么是做正确的方法是什么?

What is the correct way to do this?

推荐答案

使用 GLib.Array< T>

int main () {
    int[] x = {1, 2, 3};
    int[] y = {4, 5, 6};
    Array<int> a = new Array<int> (false, true, 0);
    a.append_vals (x, x.length);
    a.append_vals (y, y.length);
    // taking over ownership avoids array copying
    int[] z = (owned) a.data; 

    foreach (var i in z) {
        stdout.printf ("%d ", i);
    }
    stdout.printf ("\n");

    return 0;
}

精灵版本:

[indent=4]

init
    x: array of int = {1, 2, 3}
    y: array of int = {4, 5, 6}
    var a = new Array of int (false, true, 0)
    a.append_vals (x, x.length)
    a.append_vals (y, y.length)
    z: array of int = (owned) a.data

更新:在<一个href=\"http://stackoverflow.com/questions/31386774/genie-why-this-function-return-an-owned-value\">answering这个问题我已经修改了上面的code使用(独资)这避免了uneccessary阵列复制操作。

Update: After answering this question I have modified the above code to use (owned) which avoids an uneccessary array copy operation.

新的Array&LT; T&GT; 还增加了一些开销分配一个对象,但应该是在大多数情况下没有问题

The new Array<T> still adds some overhead for allocating an object, but that should be no problem in most cases.

使用 Memory.copy 是危险的,因为它可以导致各种内存问题。

Using Memory.copy is dangerous as it can cause all sorts of memory problems.

这篇关于如何连接两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆