What's the most efficient way to round robin values in a vector?

Hi all,

I have a vector of items, and for every iteration of a long running loop I need to pick an item from the vector. A randomly selected item would do, as would a simple round robin where after selecting the last entry in a vector, it will next select the first.

I've looked at a number of different data structures but I get the feeling I'm missing the magic keyword.

I know I can implement something to do this myself but I'd prefer something standard and off the shelf :grinning:

Any pointers gratefully received :grinning:

If going in order infinitely works you can use the cycle method on Iterator on the appropriate iterator from the Vec to create an iterator that does just that.

You'll have to ensure the Vec stays alive the whole time the iterator does, which depending on how things are set up now could be a little annoying.

2 Likes

Are you removing items?

Can you just keep a counter i: usize , increment it, and mod it length of the Vector ?

I'm going to go with cycle as I'm not removing anything from the vector, and although I can just use counter mod length, I was hoping to find something more "native than that :slight_smile:

Thanks for the help! :slight_smile:

1 Like

Are you allowed to swap items in the vect? I use a shuffle for randomized traversal. Pop swap let's you eat the values as you progress, which is usually what I want, but you can swap with 'k' and advance K after each iteration.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.