next_permutation函数 in c++
2016-05-11 15:53
495 查看
C++ STL中提供了std::next_permutation与std::prev_permutation可以获取数字或者是字符的全排列,其中std::next_permutation提供升序、std::prev_permutation提供降序。
1.std::next_permutation函数原型
说明:next_permutation,重新排列范围内的元素[第一,最后一个)返回按照字典序排列的下一个值较大的组合。
返回值:如果有一个更高的排列,它重新排列元素,并返回true;如果这是不可能的(因为它已经在最大可能的排列),它按升序排列重新元素,并返回false。
2.代码实例
1 #include
2 #include /// next_permutation, sort
3 using namespace std;
4 int main () {
5 int myints[] = {1,2,3,1};
6 sort (myints,myints+4);
7
8 do {
9 cout << myints[0] << ’ ’ << myints[1] << ’ ’ << myints[2] << ’ ‘<< myints[3]<<’\n’;
10 } while ( next_permutation(myints,myints+4) ); ///获取下一个较大字典序排列
11
12 cout << “After loop: ” << myints[0] << ’ ’ << myints[1] << ’ ’ << myints[2] << ’ ‘<< myints[3] <<’\n’;
13 return 0;
14 }
输出:
1 1 2 3
1 1 3 2
1 2 1 3
1 2 3 1
1 3 1 2
1 3 2 1
2 1 1 3
2 1 3 1
2 3 1 1
3 1 1 2
3 1 2 1
3 2 1 1
After loop:1 1 2 3
3.算法实现原理
见:http://hi.baidu.com/bellgrade/item/70b65b8a7ea3c9c398255fd4
算法描述:
1、从尾部开始往前寻找两个相邻的元素
第1个元素i,第2个元素j(从前往后数的),且i
1.std::next_permutation函数原型
template <class BidirectionalIterator> bool next_permutation (BidirectionalIterator first, BidirectionalIterator last ); template <class BidirectionalIterator, class Compare> bool next_permutation (BidirectionalIterator first,BidirectionalIterator last, Compare comp);
说明:next_permutation,重新排列范围内的元素[第一,最后一个)返回按照字典序排列的下一个值较大的组合。
返回值:如果有一个更高的排列,它重新排列元素,并返回true;如果这是不可能的(因为它已经在最大可能的排列),它按升序排列重新元素,并返回false。
2.代码实例
1 #include
2 #include /// next_permutation, sort
3 using namespace std;
4 int main () {
5 int myints[] = {1,2,3,1};
6 sort (myints,myints+4);
7
8 do {
9 cout << myints[0] << ’ ’ << myints[1] << ’ ’ << myints[2] << ’ ‘<< myints[3]<<’\n’;
10 } while ( next_permutation(myints,myints+4) ); ///获取下一个较大字典序排列
11
12 cout << “After loop: ” << myints[0] << ’ ’ << myints[1] << ’ ’ << myints[2] << ’ ‘<< myints[3] <<’\n’;
13 return 0;
14 }
输出:
1 1 2 3
1 1 3 2
1 2 1 3
1 2 3 1
1 3 1 2
1 3 2 1
2 1 1 3
2 1 3 1
2 3 1 1
3 1 1 2
3 1 2 1
3 2 1 1
After loop:1 1 2 3
3.算法实现原理
见:http://hi.baidu.com/bellgrade/item/70b65b8a7ea3c9c398255fd4
算法描述:
1、从尾部开始往前寻找两个相邻的元素
第1个元素i,第2个元素j(从前往后数的),且i
相关文章推荐
- 深入理解C++中的vector类的用法及特性
- c++分离式编译模型
- C++遍历文件夹获取文件列表
- Effective C++ 学习笔记(一)
- f:\rtm\vctools\vc7libs\ship\atlmfc\src\mfc\occcont.cpp(Line:950)错误
- 第7周 C语言程序设计(新2版) 例题 1.6数组(无法编译)
- C++中的宏定义
- c语言中各个类型的sizeof长度
- 在C/C++函数中使用可变参数
- 【C语言】截取字符串实现
- 详解C++编程中的vector类容器用法
- C语言——数组与指针之动态分配一维和多维数组
- PAT (Basic Level) Practise (中文)1040. 有几个PAT(25)
- c语言基础巩固 2:完全平方
- C++与Java的区别
- 汇编学习第五课之函数调用约定:cdecl,stdcall,fastcall
- 用C++进行简单的文件I/O操作
- C++中的const限定词总结
- 使用C语言实现vector动态数组的实例分享
- C语言中exit(1)和exit(0)的区别