STL之全排列next_permutation()函数的用法
2018-03-12 16:42
639 查看
next_permutation()函数包含在< algorithm>里面
使用的基本格式为:
写一个例子吧!
经过测试呀,发现上面的写法是bug的,虽说对于像是1 2 3这样的是没问题。不过,有的数据就不行了,例如下组:
很显然这里面少了一些组合,例如0 4 2,0 2 4
这是为什么呢,后来经过参考别人的文章,发现这个next_permutation()函数是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序。
加上排序之后的代码为:
这个时候问题就解决了。
使用的基本格式为:
int a[]; do{}while(next_permutation(a + n));
写一个例子吧!
//其实这个是有bug的 #include<iostream> #include<algorithm> using namespace std; int main() { int n,a[1000]; cin >> n; for(int i = 0 ; i < n ; i++) cin >> a[i]; do{ for(int i = 0 ; i < n ; i++) cout << a[i] << " "; cout << endl; }while(next_permutation(a, a + n)); return 0; }
经过测试呀,发现上面的写法是bug的,虽说对于像是1 2 3这样的是没问题。不过,有的数据就不行了,例如下组:
很显然这里面少了一些组合,例如0 4 2,0 2 4
这是为什么呢,后来经过参考别人的文章,发现这个next_permutation()函数是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序。
加上排序之后的代码为:
#include<iostream> #include<algorithm> using namespace std; int main() { int n,a[1000]; cin >> n; for(int i = 0 ; i < n ; i++) cin >> a[i]; sort(a,a + n); do{ for(int i = 0 ; i < n ; i++) cout << a[i] << " "; cout << endl; }while(next_permutation(a, a + n)); return 0; }
这个时候问题就解决了。
相关文章推荐
- 关于全排列 next_permutation() 函数的用法
- 关于全排列 next_permutation() 函数的用法
- STL快速全排列函数next_permutation与pre_permutation
- stl全排列next_permutation()与prev_permutation()函数用法
- 关于全排列 next_permutation() 函数的用法
- [STL]next_permutation全排列
- C++ STL next_permutation() & prev_permutation()函数
- 全排列 next_permutation 简单用法
- C++STL中全排列函数next_permutation的使用
- C++STL中全排列函数next_permutation的使用
- 枚举全排列 STL next_permutation
- C++ STL next_permutation() prev_permutation(a,a+n)用法。
- 全排列函数next_permutation的用法
- stl全排列 qsort+next_permutation(a,a+n) -->全排列
- STL 排序算法之全排列sort和next_permutation
- 用STL的next_permutation算法实现全排列
- C++ STL, next_permutation用法。
- 打印全排列和stl::next_permutation
- 计算下一个全排列(以STL中的next_permutation为例)
- STL中next_permutation用法小结和小技巧总结与原理。