sv--关联数组

关联数组

当集合大小未知或数据空间稀疏时,关联数组是更好的选择。关联数组在使用之前不会分配任何存储,并且索引表达式不限于整型表达式,但可以是任何类型的。

关联数组的语法

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
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值