Associative Array

Associative Array :

  • Index itself associates the data,so called as associative array.
  • Data stored in random fashion.
  • Allocate the storage only when it is used.
  • Array index can be any type.

Why Associative Array :

  • When the size of the collection is unknown an associative array is a best option.
  • Used when we don’t have to allocate contiguous collection of data.

Syntax :

data_type array_name [key];

data_type is the data type of the array elements.
array_name is the name of the assoc array.
key is the data-type to be used.

Inbuild methods :

num() or size() :: It returns the number of entries in the associative array.
delete()              :: It removes the entry at the specified index.
exists()               :: This function checks whether an element exists at the specified index within the given array.
first()                  :: This method assigns to the given index variable the value of the first (smallest) index in the associative array. It returns 0 if the array is empty; otherwise, it returns 1.
last()                   :: This method assigns to the given index variable the value of the last (largest) index in the associative array. It returns 0 if the array is empty; otherwise, it returns 1.
next()                  :: This method finds the entry whose index is greater than the given index. If there is a next entry, the index variable is assigned the index of the next entry, and the function returns 1. Otherwise, the index is unchanged, and the function returns 0.
prev()                  :: This function finds the entry whose index is smaller than the given index. If there is a previous entry, the index variable is assigned the index of the previous entry, and the function returns 1. Otherwise, the index is unchanged, and the function returns 0.

Example :

module assoc_array;
int temp,assoc_arr[*];
initial
begin

 // Assoc array Initialization
assoc_arr[ 2’d3 ]        = 1;
assoc_arr[ 16’hffff ]   = 2;
assoc_arr[ 4’b1000 ] = 3;

  $display( “%0d entries initialized”, assoc_arr.num);

 // Check whether particular index is present
  if(assoc_arr.exists( 4’b1000) )
      $display(“assoc_arr.exists( 4b’1000) “);

assoc_arr.delete(4’b1000);

   if(assoc_arr.exists( 4’b1000) )
       $display(” assoc_arr.exists( 4b’1000) “);
   else
       $display(” ( 4b’1000) not existing”);

 // First and next index check
   if(assoc_arr.first(temp))
    $display(” First entry is at index %0db “,temp);
    if(assoc_arr.next(temp))
    $display(” Next entry is at index %0h after the index 3″,temp);

// To print all the elements alone with its index
  if (assoc_arr.first(temp) )
  do
  $display( “%d : %d”, temp, assoc_arr[temp] );
  while ( assoc_arr.next(temp) );
  end
endmodule

Output Result :

3 entries initialized
assoc_arr.exists( 4b’1000)
( 4b’1000) not existing
First entry is at index 3b
Next entry is at index ffff after the index 3
3 : 1
65535 : 2