@@ -11,12 +11,12 @@ pub fn MyList(comptime T: type) type {
11
11
return struct {
12
12
const Self = @This ();
13
13
14
- nums : []T = undefined , // 数组(存储列表元素)
15
- numsCapacity : usize = 10 , // 列表容量
16
- numSize : usize = 0 , // 列表长度(即当前元素数量)
17
- extendRatio : usize = 2 , // 每次列表扩容的倍数
14
+ nums : []T = undefined , // 数组(存储列表元素)
15
+ numsCapacity : usize = 10 , // 列表容量
16
+ numSize : usize = 0 , // 列表长度(即当前元素数量)
17
+ extendRatio : usize = 2 , // 每次列表扩容的倍数
18
18
mem_arena : ? std.heap.ArenaAllocator = null ,
19
- mem_allocator : std.mem.Allocator = undefined , // 内存分配器
19
+ mem_allocator : std.mem.Allocator = undefined , // 内存分配器
20
20
21
21
// 构造函数(分配内存+初始化列表)
22
22
pub fn init (self : * Self , allocator : std.mem.Allocator ) ! void {
@@ -47,14 +47,14 @@ pub fn MyList(comptime T: type) type {
47
47
// 访问元素
48
48
pub fn get (self : * Self , index : usize ) T {
49
49
// 索引如果越界则抛出异常,下同
50
- if (index >= self .size ()) @panic ("索引越界" );
50
+ if (index < 0 or index >= self .size ()) @panic ("索引越界" );
51
51
return self .nums [index ];
52
52
}
53
53
54
54
// 更新元素
55
55
pub fn set (self : * Self , index : usize , num : T ) void {
56
56
// 索引如果越界则抛出异常,下同
57
- if (index >= self .size ()) @panic ("索引越界" );
57
+ if (index < 0 or index >= self .size ()) @panic ("索引越界" );
58
58
self .nums [index ] = num ;
59
59
}
60
60
@@ -69,7 +69,7 @@ pub fn MyList(comptime T: type) type {
69
69
70
70
// 中间插入元素
71
71
pub fn insert (self : * Self , index : usize , num : T ) ! void {
72
- if (index >= self .size ()) @panic ("索引越界" );
72
+ if (index < 0 or index >= self .size ()) @panic ("索引越界" );
73
73
// 元素数量超出容量时,触发扩容机制
74
74
if (self .size () == self .capacity ()) try self .extendCapacity ();
75
75
// 索引 i 以及之后的元素都向后移动一位
@@ -84,7 +84,7 @@ pub fn MyList(comptime T: type) type {
84
84
85
85
// 删除元素
86
86
pub fn remove (self : * Self , index : usize ) T {
87
- if (index >= self .size ()) @panic ("索引越界" );
87
+ if (index < 0 or index >= self .size ()) @panic ("索引越界" );
88
88
var num = self .nums [index ];
89
89
// 索引 i 之后的元素都向前移动一位
90
90
var j = index ;
@@ -125,10 +125,6 @@ pub fn MyList(comptime T: type) type {
125
125
126
126
// Driver Code
127
127
pub fn main () ! void {
128
- // 查看本地CPU架构和操作系统信息
129
- var native_target_info = try std .zig .system .NativeTargetInfo .detect (std.zig.CrossTarget {});
130
- std .debug .print ("Native Info: CPU Arch = {}, OS = {}\n " , .{native_target_info .target .cpu .arch , native_target_info .target .os .tag });
131
-
132
128
// 初始化列表
133
129
var list = MyList (i32 ){};
134
130
try list .init (std .heap .page_allocator );
@@ -176,5 +172,4 @@ pub fn main() !void {
176
172
std .debug .print (" ,容量 = {} ,长度 = {}\n " , .{list .capacity (), list .size ()});
177
173
178
174
_ = try std .io .getStdIn ().reader ().readByte ();
179
- }
180
-
175
+ }
0 commit comments