关联数组
当集合大小未知或数据空间稀疏时,关联数组是更好的选择。关联数组在使用之前不会分配任何存储,并且索引表达式不限于整型表达式,但可以是任何类型的。
关联数组的语法
data_type name [data_type];
int test [int];
关联数组的示例
[代码示例]
`timescale 1ns / 1ps
//
module tb( );
string data [int];
int array1 [int];
string array2 [string];
initial begin
data = '{1:"hi",
2:"verilog"};
array1 = '{1:1,
2:2,
6:6};
array2 = '{"good":"day"};
$display("data = %p",data);
$display("array1 = %p",array1);
$display("array2 = %p",array2);
end
endmodule
[代码结果]
Compiler version S-2021.09; Runtime version S-2021.09; Oct 16 03:36 2023
data = '{0x1:"hi", 0x2:"verilog"}
array1 = '{0x1:1, 0x2:2, 0x6:6}
array2 = '{"good":"day"}
V C S S i m u l a t i o n R e p o r t
Time: 0 ns
CPU Time: 0.400 seconds; Data structure size: 0.0Mb
Mon Oct 16 03:36:40 2023
Done
关联数组的内建方法
function int num () | 返回关联数组中的条目数,如果为空返回 0 |
---|---|
function int size () | 还返回条目数,如果为空返回 0 |
function void delete ( [input index] ) | 指定索引时删除该索引处的条目,否则将删除整个数组 |
function int exists (input index); | 检查指定索引处是否存在元素;如果是,则返回 1,否则返回 0 |
[代码示例] |
module tb;
// associative array
int array1 [string];
initial begin
array1 = '{"plum":5,
"orange":10,
"apple":8 };
$display("array1.num = %0d",array1.num());
$display("array1.size = %0d",array1.size());
$display("array1.exists = %0d",array1.exists (1));
$display("array1.exists = %0d",array1.exists ("plum"));
array1.delete ("orange");
$display("array1 = %0p",array1);
end
endmodule
[代码结果]
Contains Synopsys proprietary information.
Compiler version S-2021.09; Runtime version S-2021.09; Oct 16 04:02 2023
array1.num = 3
array1.size = 3
array1.exists = 0
array1.exists = 1
array1 = '{"apple":8, "plum":5}
V C S S i m u l a t i o n R e p o r t
Time: 0 ns
CPU Time: 0.460 seconds; Data structure size: 0.0Mb
Mon Oct 16 04:02:22 2023
Done