C++ List Shuffle

目前C++只提供了可随机访问的容器的shuffle接口,对于List容器该接口不可用,这里提供一个List shuffle函数模板

一、随机访问容器shuffle

1
2
3
4
5
# 生成随机种子
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

# 使用默认的随机引擎来打乱容器中的元素
std::shuffle(v.begin(), v.end(), std::default_random_engine(seed));

二、List shuffle函数模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template < typename T > void list_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) ;
}

参考

【0】 how to shuffle a list?