问题
[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