1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C++标准库---排列元素next_permutation()prev_permutation()

C++标准库---排列元素next_permutation()prev_permutation()

时间:2023-12-28 03:33:23

相关推荐

C++标准库---排列元素next_permutation()prev_permutation()

bool next_permutation(beg,end)

bool prev_permutation(beg,end)

next_permutation()会改变区间[beg,end)内的元素次序,使它们符合“下一个排列次序”;

prev_permutation()会改变区间[beg,end)内的元素次序,使它们符合“上一个排列次序”;

如果元素得以排列成(就字典顺序而言的)"正规"次序,则两个算法都返回true。所谓正规次序,对next_permutation()而言为升序,对perv_permutation()而言为降序。因此,如果要走遍所有排列,你必须先将所有元素(按升序或降序)排序,然后开始以循环方式调用next_permutation或prev_permutation,直到算法返回false;

复杂度:线性

代码示例:

#include"fuzhu.h"using namespace std;int main(){vector<int> coll;INSERT_ELEMENTS(coll,1,3);PRINT_ELEMENTS(coll,"on entry: ");//1 2 3while(next_permutation(coll.begin(),coll.end()))//从小到大,输出到3 2 1 后,再次执行next_permutation()后为false,执行后为 1 2 3{PRINT_ELEMENTS(coll," ");}PRINT_ELEMENTS(coll,"afterward: ");//1 2 3while(prev_permutation(coll.begin(),coll.end()))//未输出,因为1 2 3的上一个序列为3 2 1,不满足降序,虽然返回为flase,但是序列会变为3 2 1{PRINT_ELEMENTS(coll," ");}PRINT_ELEMENTS(coll,"now: ");//3 2 1while(prev_permutation(coll.begin(),coll.end()))//从大到小{PRINT_ELEMENTS(coll);}PRINT_ELEMENTS(coll,"afterward: ");//3 2 1system("pause");return 0;}

运行结果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。