How to concatenate two arrays?

泪湿孤枕 提交于 2019-12-08 05:13:17

问题


[indent=4]

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

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

The error message is:

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

What is the correct way to do this?


回答1:


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.



来源:https://stackoverflow.com/questions/31357727/how-to-concatenate-two-arrays

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