0

In SystemVerilog, I have a dynamic array of ints. I need to modify this array so as to skip the first 2 elements. For backward compatibility, I cannot change the data type to a queue. (which would allow me to do pop_front). So I came up with this hacky code that copies the array at least twice. Is there a better way?

tmp_arr = new[dyn_arr.size() -2];         
for(int i = 0; i < tmp_arr.size(); i++) begin
  tmp_arr[i] = dyn_arr[i + 2];           // First Copy
end
dyn_arr = tmp_arr;                       // Second Copy

My test is also on edaplayground. https://www.edaplayground.com/x/2VPm

2 Answers 2

2

Not really. The streaming operator can do this but might be more expensive.

You might try

for(int i=2;i < dyn_arr.size(); i++)
   dyn_arr[i-2] = dyn_arr[i];
dyn_arr = new[dyn_arr.size-2] dyn_arr;

And hope the compiler is smart enough to optimize that without copying.

Sign up to request clarification or add additional context in comments.

Comments

1

Depending on how much support your tools have for the stream operator, you can just use that like so:

dyn_arr = {>>$size(dyn_arr[0]){dyn_arr with [2:dyn_arr.size()-1]}};

This assumes the dyn_arr is at least 3 elements long (ie, that the resulting array will be at least 1 element long).

Otherwise, you can always just use a loop to shift the whole array down rather than making a new one:

for (int i = 2; i < dyn_arr.size(); i++) begin
  dyn_arr[i - 2] = dyn_arr[i];
end
dyn_arr = new[dyn_arr.size()-2] (dyn_arr); // Only include this if you need to use dyn_arr.size with the smaller size after the operation is complete

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.