Friday, March 02, 2012

Assosiative array Methods

Associative Array Methods

In addition to the indexing operators, several built-in methods are provided that allow users to analyze and manipulate associative arrays, as well as iterate over its indices or keys.

num()

The syntax for the num() method is:

function int num();

The num() method returns the number of entries in the associative array. If the array is empty, it returns 0.

int imem[*];
imem[ 2’b3 ] = 1;
imem[ 16’hffff ] = 2;
imem[ 4b’1000 ] = 3;
$display( "%0d entries\n", imem.num ); // prints "3 entries"

delete()

The syntax for the delete() method is:

function void delete( [input index] );

Where index is an optional index of the appropriate type for the array in question.

If the index is specified, then the delete() method removes the entry at the specified index. If the entry to be deleted does not exist, the method issues no warning. If the index is not specified, then the delete() method removes all the elements in the array.

int map[ string ];
map[ "hello" ] = 1;
map[ "sad" ] = 2;
map[ "world" ] = 3;
map.delete( "sad" ); // remove entry whose index is "sad" from "map"
map.delete; // remove all entries from the associative array "map"

exists()

The syntax for the exists() method is:

function int exists( input index );

Where index is an index of the appropriate type for the array in question.

The exists() function checks if an element exists at the specified index within the given array. It returns 1 if the element exists, otherwise it returns 0.

if ( map.exists( "hello" ))
map[ "hello" ] += 1;
else
map[ "hello" ] = 0;

first()

The syntax for the first() method is:

function int first( ref index );

The first() 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, and 1 otherwise.

string s;
if ( map.first( s ) )
$display( "First entry is : map[ %s ] = %0d\n", s, map[s] );

last()

The syntax for the last() method is:

function int last( ref index );

Where index is an index of the appropriate type for the array in question.

The last() 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, and 1 otherwise.

string s;
if ( map.last( s ) )
$display( "Last entry is : map[ %s ] = %0d\n", s, map[s] );

No comments:

Post a Comment

Popular Posts