sv中的新数据类型queue/关联数组

1,014 阅读1分钟

sv中的新数据类型

1. 静态数组/动态数组/关联数组

  • 队列:像动态数组一样,队列可以增长和缩小,但是队列可以很方便地添加和删除元素。b[$] = {3,4};

  • 关联数组:

    • 如果想要处理具有数千兆字节范围的地址,而实际执行中只会涉及到部分地址,此时创建一个大型数组分配和初始化千兆字节会非常浪费。
    • SystemVerilog提供了关联数组数据结构。SystemVerilog仅在写入元素时为其分配内存。如下图,关联数组保存值0:3,42,1000,4521和200,000。 用于存储这些数据的内存远远少于存储200,000个数据的固定或动态数组内存
    • 下面是关联数组的声明,初始化和执行。关联数组使用 [*]声明。
initial begin
logic [63:0] assoc[*], idx = 1;
// Initialize widely scattered values
repeat (64) begin
assoc[idx] = idx;
idx = idx << 1;
end
// Step through all index values with foreach
foreach (assoc[i])
$display("assoc[%h] = %h", i, assoc[i]);
// Step through all index values with functions
if (assoc.first(idx))
begin // Get first index
do
$display("assoc[%h]=%h", idx, assoc[idx]);
while (assoc.next(idx)); // Get next index
end
// Find and delete the first element
assoc.first(idx);
assoc.delete(idx);
end
//关联数组的声明,初始化,使用;关联数组用来保存稀疏矩阵的元素
//声明:在方括号中放置数据类型的形式来声明,也可以用通配符作为下标来进行声明(不建议这样是使用)
//可以使用函数exists()这个函数来检查元素是否存在,如果元素尚未被写入,SV会返回数组类型的缺省值,对双状态是0,对于四状态是X,即未知态
module test;
initial begin 
bit [63:0] assoc[bit[63:0]],idx=1;
//对稀疏矩阵元素进行初始化
repeat(64) begin
	assoc[idx] = idx;
	idx = idx << 1;//每次左移一位
end
//使用foreach遍历数组
$display("this is 1:");
foreach(assoc[i])
	$display("assoc[%h]=%h",i,assoc[i]);//这里使用16进制打印,每4位代替16二进制
	
//使用函数遍历数组,first和next函数会返回1或0;
$display("this is 2:");
if(assoc.first(idx))begin
	do 
		$display("assoc[%d]=%d",idx,assoc[idx]);//这里按10进制打印
		while(assoc.next(idx));//得到下一个索引
	end
	
//找到第一个元素
assoc.first(idx);
//删除第一个元素
assoc.delete(idx);
$display("The array now has %0d elements",assoc.num);
end 
endmodule