next_permutation 求下一组合 函数

next_permutation 位于algorithm算法库中

支持传入需要遍历的范围 且对原数据会进行修改

若无下次可能的排列 则返回false,所以常与while搭配使用

该函数也支持字符遍历,因为底层通过字典序进行遍历

此外使用该函数前必须从字典序排好序 否则只会遍历未排序之后的情况

#include "iostream"
#include "algorithm"
using namespace std;
int main(){
    int num[4]={1,2,3,4};
    while (next_permutation(num,num+4)){
        cout<<num[0]<<num[1]<<num[2]<<num[3]<<endl;
    }
}

输出

1243
1324
1342
1423
1432
2134
2143
2314
2341
2413 等.....

与之对应的还有 prev_permutation()

寻找上一个排列 用法相同

posted @ 2023-01-14 15:02  Cheng_Mao  阅读(15)  评论(0)    收藏  举报