C++ next_permutation
・next_permutationをつかい配列の要素の順列をすべて確認する
next_permutationというSTLを使うと配列内の要素の順列をすべて確認できます
配列内の要素はソートされていないと全通りためしてくれませんので注意!
vector<int> vec; for(int i=0;i<3;i++) vec.push_back(i); do { //vecの中身が毎回変化し、全通りためしてくれる //このときvec内は次のように変化する // {0,1,2} -> {0,2,1} -> {1,0,2} -> {1,2,0} -> {2,0,1} -> {2,1,0} }while(next_permutation(vec.begin(),vec.end())); //この時点でvec内の要素は初期の状態{0,1,2}に戻っている
ちなみにnext_permutationのテンプレートは次のようになっているので、自分でCompareを実装することで順番を逆にしたりなんだりできます
もちろんその時は配列のソートもそれに対応した形にしないといけません
template<typename BidiIter,typename Compare>
bool next_permutation(BidiIter first,BidiIter last);
template<typename BidiIter,typename Compare>
bool next_permutation(BidiIter first,BidiIter last,Compare comp);