The next() method finds the smallest index whose value is greater than the given index argument.
The prev() method finds the largest index whose value is smaller than the given index argument.
int array='{"apple":1,"guava":4,"orange":5,"grapes":7}
string k = "guava";]
int c;
initial begin
c = array.prev(k); // k becomes "grapes"
c = array.next(k); // k becomes "guava"
end
fruits= '{“apple”:6,“orange”:2, “guava”:3, “watermelon”: 9,“grape”:1};
//OUTPUT//
Previous fruit of guava is [grape] = 1
Next fruit of guava is [guava] = 3
My understandings.
index of apple=0,
index of orange=1,
index of guava=2,
index of watermelon=3,
index of grape=4,
The next() method finds the smallest index whose value is greater than the given index argument.
=> value greater than guava’s(3) :apple(6),watermelon(9) but here smallest index is apple
The prev() method finds the largest index whose value is smaller than the given index argument.
=> value smaller than guava’s(3):grape(1),orange(2) but largest index is grape.
Let me know if my understanding is correct.
If my understanding is correct then output is wrong.
Hi ,
I believe this scenario is similar to 2D vector with string-index in C++.
Here the strings are apple, orange, guava, watermelon, and grape.
Now in order to get a clear understanding of what is happening in that code, we need to look at these strings in sorted order. After sorting these strings, we get-
apple
grape
guava
orange
watermelon
If you analyze this answer, you’ll see that watermelon got the last place because its length is the highest. Then orange. Rest are arranged based on the ASCII values of each and every letter because they have the same length.
Go through this code for a better understanding.
// Associative array //
module associative_array();
int fruits[string];
initial begin
fruits= '{"apple":6,"orange":2, "guava":3, "watermelon": 9,"grape":1};
begin
string f; // Default value of f would be lowest index i.e. "apple"
while(fruits.next(f))
$display(" Next fruit of is [%s] = %0d",f,fruits[f]);//It'll stop as it's not cyclic in nature unlike enum
end
end
endmodule
//ANSWER
# Loading sv_std.std
# Loading work.associative_array(fast)
#
# vsim -voptargs=+acc=npr
# run -all
# Next fruit of is [apple] = 6
# Next fruit of is [grape] = 1
# Next fruit of is [guava] = 3
# Next fruit of is [orange] = 2
# Next fruit of is [watermelon] = 9
# exit
# End time: 11:02:46 on Feb 27,2023, Elapsed time: 0:00:01
# Errors: 0, Warnings: 0