GeezerVison is showing cpprefjp.github.io — std::shuffle - cpprefjp C++日本語リファレンス
最終更新日時:
2026年08月26日 16時18分05秒 (JST)
Akira Takahashi
が更新
履歴
編集
function template
<algorithm>
std:: shuffle (C++11)
namespace std {
template < class RandomAccessIterator , class UniformRandomBitGenerator >
void shuffle ( RandomAccessIterator first , RandomAccessIterator last ,
UniformRandomBitGenerator && g );
}
概要
[first,last) のそれぞれの要素を同じ確率で並び替える。
要件
RandomAccessIterator は ValueSwappable の要件を満たしている必要がある。
UniformRandomBitGenerator は uniform random bit generator の要件を満たさなければならず、その戻り値の型は iterator_traits <RandomAccessIterator>::difference_type へ変換可能でなければならない。
計算量
正確に (last - first) - 1 回 swap する。
備考
以下の実装では、フィッシャー - イェーツのシャッフル アルゴリズムが使用されている:
GCC: 4.9 (libstdc++)
Clang: 3.4 (libc++)
Visual C++: 2013
例
整数の配列をシャッフルする
出力例
before: 0123456789
after: 5803429716
文字列をシャッフルする
出力例
before: 0123456789abcdef
after: 49e351b8f0ad62c7
実装例
template < class RandomAccessIterator , class UniformRandomBitGenerator >
void shuffle ( RandomAccessIterator first , RandomAccessIterator last , UniformRandomBitGenerator && g ) {
if ( first == last ) return ;
using distance_type = typename iterator_traits < RandomAccessIterator >:: difference_type ;
using unsigned_type = typename make_unsigned < distance_type >:: type ;
using distribute_type = uniform_int_distribution < unsigned_type > ;
using param_type = typename distribute_type :: param_type ;
distribute_type d ;
for ( auto it = first + 1 ; it != last ; ++ it )
iter_swap ( it , first + d ( g , param_type ( 0 , it - first )));
}
関連項目
参照