關聯數組定義
在 SystemVerilog 中,關聯數組(Associative Arrays)是一種非常靈活的數據結構,它可以使用任意類型的鍵(key)來索引數組中的元素。這使得關聯數組特別適合于實現類似哈希表(hash tables)或字典(dictionaries)的功能,其中鍵可以是字符串、數字或其他復雜類型。
data_type array_name [index_type];//data_type:數組元素的數據類型。//array_name:關聯數組的名稱。//index_type:關聯數組索引的數據類型,可以是任何類型,包括整型、字符串、結構體、類等。如果索引類型為*,則表示索引可以是任何integral類型。關聯數組可以在聲明時通過花括號{}進行初始化,初始化時列出所有的鍵值對,鍵值對之間用逗號分隔。例如:int my_array[string] = '{"apple": 1, "banana": 2, "orange": 3};// 訪問
int value = my_array["banana"]; // 修改
my_array["apple"] = 5;//使用foreach循環遍歷:
foreach (my_array[key]) begin $display("my_array[%s] = %0d", key, my_array[key]);
end
//使用first、next方法遍歷:
string key;
if (my_array.first(key)) begin $display("my_array[%s] = %0d", key, my_array[key]);
end
//num():返回數組中元素的數量。
//exists(index):檢查數組中是否存在指定索引的元素。
//delete(index):刪除數組中指定索引的元素。如果不帶索引號調用,則會清空整個數組。
舉例
module associative_array_example;// 聲明一個關聯數組,鍵為字符串類型,值為整數類型int my_assoc[string];// 初始化數組initial begin// 添加鍵值對my_assoc["one"] = 1;my_assoc["two"] = 2;my_assoc["three"] = 3;// 檢查鍵是否存在if (my_assoc.exists("one")) begin$display("Key 'one' exists.");end// 訪問數組中的值$display("Value for 'two': %0d", my_assoc["two"]);// 刪除一個鍵值對my_assoc.delete("three");// 遍歷數組中的所有鍵值對foreach (my_assoc[key]) begin$display("Key: %s, Value: %0d", key, my_assoc[key]);endendendmodule
module test;initial beginbit (63:0) assoc(bit(63:0)), idx = 1; // 初始化關聯數組,索引為 63 位的位向量// 初始化一些零散的值repeat(64) beginassoc(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
module associative_array_example;// 聲明一個關聯數組,鍵為字符串類型,值為整數類型int my_assoc[string];// 初始化數組initial begin// 添加鍵值對my_assoc["apple"] = 5;my_assoc["banana"] = 3;string key = "apple";// 檢查鍵是否存在if (my_assoc.exists(key)) begin$display("The key '%s' exists in the associative array.", key);// 如果鍵存在,可以繼續讀取或修改值$display("Value for '%s': %0d", key, my_assoc[key]);end else begin$display("The key '%s' does not exist in the associative array.", key);endendendmodule