当前位置: 首页 > news >正文

STL—next_permutation函数

目录

1.next_permutation函数的定义

2.简单使用

2.1普通数组全排列

 2.2结构体全排列

2.3string

3.补充


1.next_permutation函数的定义

next_permutation函数会按照字母表顺序生成给定序列的下一个较大的排列,直到整个序列为降序为止。与其相对的还有一个函数——prev_permutation函数。

next_permutaion(起始地址,末尾地址+1)
next_permutaion(起始地址,末尾地址+1,自定义排序)

注:next_permutation只能获得上一个排列,如果要获得全排列,那么就需要先对数组进行升序排序

2.简单使用

2.1普通数组全排列

#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>
#include <algorithm>
using namespace std;int main()
{int arr[4] = { 1, 2, 3, 4 };do {for (int i = 0; i < 4; i++){cout << arr[i] << " ";}cout << endl;} while (next_permutation(arr, arr + 4));return 0;
}

 运行结果:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

 2.2结构体全排列

由于结构体默认不能比较大小,所以就不能使用默认的next_permutation()排列比较函数,需要使用自定义排列比较函数。

#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>
#include <algorithm>
using namespace std;typedef struct
{int test;bool operator < (const fyd& a){return test < a.test;}}fyd;fyd arr[4];int main()
{arr[0].test = 2;arr[1].test = 1;arr[2].test = 4;arr[3].test = 3;do {for (int i = 0; i < 4; i++){cout << arr[i].test << " ";}cout << endl;} while (next_permutation(arr, arr + 4));return 0;
}

运行结果:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

2.3string

string等数据结构不能直接用名字代表地址,只能够使用自带的迭代器begin()、end()实现全排列。

#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>
#include <algorithm>
using namespace std;int main()
{string s;cin >> s;do{cout << s << endl;}while (next_permutation(s.begin(), s.end()));return 0;
}

运行结果:

abc //inputabc
acb
bac
bca
cab
cba

3.补充

推荐大家使用:cplusplus.com - The C++ Resources Network

可以查询到对应函数对应的头文件、底层代码及使用方式等。

例如:

 剩下的就不多说啦!自己探索叭!

http://www.lryc.cn/news/231413.html

相关文章:

  • Mysql 三种不使用索引的情况
  • Ladybug 全景相机, 360°球形成像,带来全方位的视觉体验
  • centos 6.10 安装swig 4.0.2
  • mask: rle, polygon
  • 【JMeter】JMeter压测过程中遇到Non HTTP response code错误解决方案
  • 【Kingbase FlySync】评估工具安装及使用
  • pandas教程:Data Aggregation 数据聚合
  • 开启创造力之门:掌握Vue中Slot插槽的使用技巧与灵感
  • 【算法练习Day48】回文子串最长回文子序列
  • ubuntu下C++调用matplotlibcpp进行画图(超详细)
  • 芯科科技推出新的8位MCU系列产品,扩展其强大的MCU平台
  • Flink CDC
  • 数据结构-链表的简单操作代码实现3-LinkedList【Java版】
  • JTS: 24 MinimumDiameter 最小矩形
  • MacOS Ventura 13 优化配置(ARM架构新手向导)
  • 多区域OSPF配置
  • 【强化学习】day1 强化学习基础、马尔可夫决策过程、表格型方法
  • openwrt Docker不能联网
  • EtherCAT从站EEPROM组成信息详解(2):字8-15产品标识区
  • SpringBoot--中间件技术-4:整合Shiro,Shiro基于会话SessionManager实现分布式认证,附案例含源代码!
  • 【QT基础入门】QT中的容器类
  • IDEA没有Add Framework Support解决办法
  • 《009.SpringBoot之汽车租赁系统》
  • 第四代智能井盖传感器,万宾科技助力城市安全
  • ClickHouse 面试题
  • Python代码运行速度提升技巧!Python远比你想象中的快~
  • P6入门:项目初始化11-项目详情之计算Calculations
  • <MySQL> 查询数据进阶操作 -- 联合查询
  • centos 6.10 安装 svn1.14.2
  • Java实现俄罗斯方块