template < typename T > void shuffle( std::list<T>& lst ) // shuffle contents of a list
{
// create a vector of (wrapped) references to elements in the list
// http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
std::vector< std::reference_wrapper< const T > > vec( lst.begin(), lst.end() ) ;
// shuffle (the references in) the vector
std::shuffle( vec.begin(), vec.end(), std::mt19937{ std::random_device{}() } ) ;
// copy the shuffled sequence into a new list
std::list<T> shuffled_list { vec.begin(), vec.end() } ;
// swap the old list with the shuffled list
lst.swap(shuffled_list) ;
}
Note: This would be more efficient if copying the value_type of the list is expensive, but it is movable.
If move semantics is uncharted waters for you, ignore this for now.
1 2 3
// copy the shuffle sequence into a new list
std::list<T> shuffled_list ; // { vec.begin(), vec.end() } ;
for( auto& ref : vec ) shuffled_list.push_back( std::move( ref.get() ) ) ;