The best and most concise way to find the value of the last element in an associative array?

In reply to rgarcia07:

Hi,

Thank you for the reply. Let me answer your questions.

From which LRM section you got that the find_last() method is for associative arrays?
Array locator methods (find_last() is one of them) operate on any unpacked array, including queues, they return a queue, which makes the code you posted as second method not to make sense since you are casting a queue to an int.

Answer: You were already in the correct location of LRM. Just further read on the next page, and you will see this sentence stating .find_last supports associative arrays as below.

Index locator methods return a queue of int for all arrays except associative arrays, which return a queue of the same type as the associative index type. Associative arrays that specify a wildcard index type shall not be allowed.

Next question:

What exactly you mean by the last element in an associative array? Also I think you could be misinterpreting the last() method as in the LRM is stated that it returns the last (largest)index or key

Answer: You’re right. I misunderstood the meaning of .last. Yes, it should be the largest index. Thanks for pointing it out.

Next one:

I do not see such a huge overhead of having one if-else, that actually takes care the possibility of having an empty array, I’m not sure in your application what is the problem, even using something like what you propose how can you tell of the array is empty or if the type doesn’t match (which I think it should be an error detected at compile time, instead of handling this especial case of truncation for integral type indexes described in the LRM)

Answer: I just don’t like to declare a new variable only for this purpose, especially in the middle of a thread, where I have to put the code into a new “begin-end” block or move the declaration to the very beginning of the thread. I agree it is not a big overhead, though I prefer a one-line way.

Regarding the empty checks, I think if .find_last with (1) returns an empty array, it is sufficient to tell us the associative array is also empty.