next_permutation()—遍历全排列
next_permutation()--遍历全排列
template <class BidirectionalIterator>
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last);
template <class BidirectionalIterator, class Compare>
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last, Compare comp);
如果可以继续遍历则返回True,否则返回False,直到数组从增序一直遍历到减序.
示例:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
char arr[] = {'A', 'B', 'C'};
// int arr[] = {1, 2, 3};
// string arr[] = {"A", "B", "C"};
sort(arr, arr+3);
// 排序保证数组顺序为增序,这样才可以把全排列遍历完.
do {
cout << arr[0] << arr[1] << arr[2] << endl;
} while (next_permutation(arr, arr+3));
cout << "After Loop: " << arr[0] << arr[1] << arr[2] << endl;
return 0;
}
结果:
ABC
ACB
BAC
BCA
CAB
CBA
After Loop: ABC