This commit is contained in:
krahets
2023-03-15 03:12:57 +08:00
parent 000a583f92
commit 683e7ee872
7 changed files with 138 additions and 130 deletions

View File

@@ -1562,9 +1562,9 @@ comments: true
const Self = @This();
nums: []T = undefined, // 数组(存储列表元素)
numsCapacity: usize = 10, // 列表容量
numSize: usize = 0, // 列表长度(即当前元素数量)
extendRatio: usize = 2, // 每次列表扩容的倍数
nums_capacity: usize = 10, // 列表容量
num_size: usize = 0, // 列表长度(即当前元素数量)
extend_ratio: usize = 2, // 每次列表扩容的倍数
mem_arena: ?std.heap.ArenaAllocator = null,
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
@@ -1574,7 +1574,7 @@ comments: true
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
self.mem_allocator = self.mem_arena.?.allocator();
}
self.nums = try self.mem_allocator.alloc(T, self.numsCapacity);
self.nums = try self.mem_allocator.alloc(T, self.nums_capacity);
std.mem.set(T, self.nums, @as(T, 0));
}
@@ -1586,12 +1586,12 @@ comments: true
// 获取列表长度(即当前元素数量)
pub fn size(self: *Self) usize {
return self.numSize;
return self.num_size;
}
// 获取列表容量
pub fn capacity(self: *Self) usize {
return self.numsCapacity;
return self.nums_capacity;
}
// 访问元素
@@ -1614,7 +1614,7 @@ comments: true
if (self.size() == self.capacity()) try self.extendCapacity();
self.nums[self.size()] = num;
// 更新元素数量
self.numSize += 1;
self.num_size += 1;
}
// 中间插入元素
@@ -1629,7 +1629,7 @@ comments: true
}
self.nums[index] = num;
// 更新元素数量
self.numSize += 1;
self.num_size += 1;
}
// 删除元素
@@ -1642,22 +1642,22 @@ comments: true
self.nums[j] = self.nums[j + 1];
}
// 更新元素数量
self.numSize -= 1;
self.num_size -= 1;
// 返回被删除元素
return num;
}
// 列表扩容
pub fn extendCapacity(self: *Self) !void {
// 新建一个长度为 size * extendRatio 的数组,并将原数组拷贝到新数组
var newCapacity = self.capacity() * self.extendRatio;
// 新建一个长度为 size * extend_ratio 的数组,并将原数组拷贝到新数组
var newCapacity = self.capacity() * self.extend_ratio;
var extend = try self.mem_allocator.alloc(T, newCapacity);
std.mem.set(T, extend, @as(T, 0));
// 将原数组中的所有元素复制到新数组
std.mem.copy(T, extend, self.nums);
self.nums = extend;
// 更新列表容量
self.numsCapacity = newCapacity;
self.nums_capacity = newCapacity;
}
// 将列表转换为数组