Array concatenation: Difference between revisions

→‎{{header|Zig}}: fix, add deinit() where appropriate, use std.mem.concat
imported>Belowdecent
(→‎{{header|Zig}}: fix, add deinit() where appropriate, use std.mem.concat)
Line 4,700:
 
=={{header|Zig}}==
There are no hidden memory allocations in Zig.
<syntaxhighlight lang="zig">const std = @import("std");
fn concat(allocator: std.mem.Allocator, a: []const u32, b: []const u32) ![]u32 {
const resultstd = try allocator.alloc@import(u32, a.len + b.len"std");
std.mem.copy(u32, result, a);
std.mem.copy(u32, result[a.len..], b);
return result;
 
pub fn main() !void {
var general_purpose_allocatorgpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const gpa = general_purpose_allocator.allocator();
 
var array1 = [_]u32{ 1, 2, 3, 4, 5 };
const allocator = gpa.allocator();
var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 };
 
const array3 = concat(gpa, &array1, &array2);
var array1 = [_]u32{ 1, 2, 3, 4, 5 };
std.debug.print("Array 1: {any}\nArray 2: {any}\nArray 3: {any}", .{ array1, array2, array3 });
var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 };
}</syntaxhighlight>
 
const array3slice3 = try std.mem.concat(gpaallocator, u32, &[_][]const u32{ &array1, &array2 });
defer allocator.free(slice3);
 
// Same result, alternative syntax
const slice4 = try std.mem.concat(allocator, u32, &[_][]const u32{ array1[0..], array2[0..] });
defer allocator.free(slice4);
 
std.debug.print(
std.debug.print( "Array 1: {any}\nArray 2: {any}\nArraynSlice 3: {any}",\nSlice .{ array1, array2, array34: {any});\n",
.{ array1, array2, slice3, slice4 },
);
}</syntaxhighlight>
{{out}}
<pre>
Array 1: { 1, 2, 3, 4, 5 }
Array 2: { 6, 7, 8, 9, 10, 11, 12 }
Slice 3: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }
Slice 4: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }
</pre>
 
=={{header|zkl}}==
59

edits