next_permutation
时间: 2023-08-28 19:07:55 浏览: 38
`next_permutation()` is a C++ STL algorithm that modifies a sequence to its lexicographically next greater permutation. In other words, it rearranges the elements in the sequence to their next greater permutation, if possible, and returns true. If the sequence is already the largest lexicographically, it rearranges it to the smallest lexicographically and returns false.
For example, consider a sequence {1, 2, 3}. The next greater permutation of this sequence is {1, 3, 2}. Similarly, the next greater permutation of {3, 2, 1} is {1, 2, 3}.
The `next_permutation()` algorithm takes two iterators as input: the first iterator points to the beginning of the sequence, and the second iterator points to the end of the sequence. It rearranges the elements in the sequence by swapping adjacent elements until it reaches the next greater permutation, or the sequence is the largest lexicographically.
Here's an example code that demonstrates the usage of `next_permutation()`:
```
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> v = {1, 2, 3};
do {
for (int i : v) {
cout << i << " ";
}
cout << endl;
} while(next_permutation(v.begin(), v.end()));
return 0;
}
```
In this example, the `do-while` loop prints all the permutations of the vector `v` by repeatedly calling `next_permutation()` until it returns false. The output of this code would be:
```
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
```