# Thread: How to randomly shuffle the elements within a QValueVector/QValueList?

1. Novice
Join Date
Nov 2006
Posts
58
Thanks
1
Qt products
Platforms

## How to randomly shuffle the elements within a QValueVector/QValueList?

Let's say, I defined a QValueVector or QValueList with "int" type elements and also put some elements into the vector/list to fulfill the stucture. Then, I need a function that can randomly shuffle the elements' sequence which is already stored in my vector/list.

Is there some available methods provided by Qt3 to do this kind of work?
BTW: I have searched through the Qt's documents, but I failed to get such functions.

Thanks a lot.

2. Expert
Join Date
Feb 2006
Location
Romania
Posts
2,744
Thanks
8
Thanked 541 Times in 521 Posts
Qt products
Platforms

## Re: How to randomly shuffle the elements within a QValueVector/QValueList?

See STL's next_permutation. But you could also create a simple algorithm of your own to generate a random permutation.

For example, if you have N elements in your initial vector, then allocate another int vector with N elements and for each index assign an random integer between 0..N-1, but make sure this is unique by testing with the previous elements. Next rearrange the elements in the first vector according to this order:
Qt Code:
`int x[] = {1, 2, 3, 4, 5};...int perm[] = {0, 2, 1, 4, 3 }`
To copy to clipboard, switch view to plain text mode
This would yield x = { 1, 3, 2, 5, 4 }

This is just to get you started. You could do without the second array.

3. ## Re: How to randomly shuffle the elements within a QValueVector/QValueList?

The easiest way is to simply call std::shuffle() on the container.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.