c++中的next_permutation
时间: 2023-05-26 16:07:18 浏览: 57
在C++中,std::next_permutation 函数是一个用于生成下一个排列的 STL 函数。该函数更新给定序列的下一个排列,从而产生字典序大于当前排列的序列。
函数原型如下:
```c++
template <class BidirectionalIterator>
bool next_permutation(BidirectionalIterator first, BidirectionalIterator last);
```
该函数接受两个迭代器作为参数,分别指向将要产生下一个排列的序列的起始位置和终止位置。函数返回值为 bool 类型,表示是否成功生成下一个排列。如果函数成功,则下一个排列的元素将存储在指定的序列中,并且函数返回 true。如果函数未能生成下一个排列,则容器中的元素将按照其初始排列的状态,函数返回 false。
示例:
```c++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v {1,2,3};
do{
for(auto i:v)
cout<<i<<" ";
cout<<'\n';
}while(next_permutation(v.begin(),v.end()));
return 0;
}
```
输出结果:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1