How to concatenate two arrays?

半世苍凉 提交于 2019-12-06 16:58:44
Jens Mühlenhoff

Using 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;
}

The Genie version:

[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

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!