#How to make a 2D ArrayList

1 messages · Page 1 of 1 (latest)

summer lotus
#

I am trying to get something similar to a C++ std::vector<std::vector<type>> and having some issues. Below is a minimally reproducible example of how I am trying to use ArrayList. The code compiles and runs, but no numbers get printed out. What is the proper way to have a type similar to std::vector<std::vector<>> in Zig. Any guidance on my misunderstanding of ArrayList is much appreciated. Thanks.

const std = @import("std");

pub fn main() !void {
    var gps = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gps.allocator();

    var array = std.ArrayList(std.ArrayList(usize)).init(allocator);

    for (0..10) |_| {
        try array.append(std.ArrayList(usize).init(allocator));
        var tmp = array.getLast();
        for (0..10) |j| {
            try tmp.append(j);
        }
    }

    for (array.items) |row| {
        std.debug.print("row: ", .{});
        for (row.items) |col| {
            std.debug.print(" {d}", .{col});
        }
        std.debug.print("\n", .{});
    }
}

topaz trail
#

your bug is that you make copies of the arraylist by doing var tmp = array.getLast()

#

not really "copies" since they point to the same bit of memory

#

but like the actually ones in array dont know that items got added

violet cobalt
#

->

for (0..10) |i| {
    try array.append(std.ArrayList(usize).init(allocator));
    for (0..10) |j| {
        try array.items[i].append(j);
    }
}
#

also youre leaking all of the allocations

dusty ore
#

can you explain the leaking? Looks fine to me, but im a Java dev and mem management is foreign territory.

violet cobalt
#

its never freed

#

you need to call deinit on each of the arraylists to free the memory they allocated