dynamic_arrays

Code

dynamic_arrays.odin ¶
62 linesSource

1package dynamic_arrays
2
3import "core:fmt"
4import "core:mem"
5
6main :: proc() {
7	// Create a dynamic array with a length of 5 and a capacity of 5.
8	dyn := make([dynamic]int, 5, 5)
9	// dyn = [0, 0, 0, 0, 0]
10
11	// Free the dynamic array.
12	defer delete(dyn)
13
14	// Add elements to the dynamic array.
15	append(&dyn, 1)
16	append(&dyn, 2)
17	// dyn = [0, 0, 0, 0, 0, 1, 2]
18
19	// Remove the last element.
20	last_element := pop(&dyn)
21	fmt.println(last_element)
22
23	// Remove the first element.
24	first_element := pop_front(&dyn)
25	fmt.println(first_element)
26	// dyn = [0, 0, 0, 0, 1]
27
28	// Add an array to the dynamic array.
29	arr: [3]int = {1, 2, 3}
30	append(&dyn, ..arr[:])
31
32	// Remove what we just added.
33	remove_range(&dyn, len(dyn) - len(arr), len(dyn))
34
35	fmt.println(dyn)
36
37	// Zero all the elements.
38	mem.zero_slice(dyn[:])
39	
40	for _, i in dyn {
41		dyn[i] = i + 1
42	}
43
44	// Maintain the order of the elements.
45	ordered_remove(&dyn, 0)
46
47	// Do not maintain the order. 
48	// This is faster since ordered_remove has to copy, 
49	// whereas this effectively swaps the last element 
50	// with that of your choice and pops it.
51	unordered_remove(&dyn, 0)
52
53	// Copy the dynamic array into dyn_copy.
54	dyn_copy := make([dynamic]int, len(dyn), cap(dyn))
55	defer delete(dyn_copy)
56	
57	copy(dyn_copy[:], dyn[:])
58	
59	fmt.println("Elements:", dyn)
60	fmt.println("Length:  ", len(dyn))
61	fmt.println("Capacity:", cap(dyn))
62}

Declarations Used 2