How to shuffle stl list of pointers in C++ ?
I have stl vector of pointers on class Player and I shuffle like
std::random_shuffle(players.begin(), players.end());
Is there already algorithm for shuffle list without requiring Random Access or I need to convert list to vector => shuffle => back to list ? Is there more elegant solution ?
The random shuffle algorithm swaps a specific element with a randomly chosen one. It would be very inefficient to repeatedly traverse the list to get the elements (namely it would be an
O(n^2)operation).That’s why it would be better (faster) to copy your list to an array once, do a random shuffle and possibly restore the list. That would be
3*ntraversals, which is stillO(n).