unique去重函数,lower_bound,upper_bound二分查找函数,sort函数,全排列

 

unique去重函数

作用是去除相邻的重复元素,只保留一个,它每次把重复的元素依次往后放,并没有真正的删除。

去重之后的数组长度为unique((a,a+n)-a);

lower_bound

lower_bound(start,end,value),在区间[start,end)中的非递减序列进行二分查找,返回大于等于value的第一个元素的位置,如果所有元素都小于value,则返回end的位置。

upper_bound(start,end,value),在区间[start,end)中的非递减序列进行二分查找,返回大于value的第一个元素的位置。

sort函数  在头文件algorithm中

bool compare(int a,int b)

{

return a>b;//若想让sort函数升序排列改为a<b即可

}

降序:sort(a,a+n,compare())

 

全排列:从n个不同元素中任取m个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时,所有的排列情况叫全排列。

公式:f(n)=n!(定义0!=1)

next_permutation()

next_permutation()函数原型为

bool next_permutation(iterator start,iterator end)

当当前序列不存在下一个排列时,函数返回false,否则返回true。

#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
  int a[3]={1,2,3};
   do
{
    printf("%d %d %d\n",a[0],a[1],a[2]);
}
while(next_permutation(a,a+3);
return 0
}

next_permutation(a,a+3),参数3指的是要排序的长度。

例如:next_permutation(a,a+2),结果为 123 213,只对前两个数进行全排列。

 如果用next_permutation(str,str+4),只输入123,就会出现错误。因为str中的第四个元素指向未知的地方。

由此可知,next_permutation(a,a+n)函数是对数组a中的前n个元素进行全排列,同时并改变a数组的值。

需注意的是:next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。

prev_permutation()

求由原排列得到的序列中上一次最近序列。

#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
  int a[3]={3,2,1};
   do
{
    printf("%d %d %d\n",a[0],a[1],a[2]);
}
while(prev_permutation(a,a+3);
return 0
}

输出:312 231 132 123

若输入123,不输出,因为123没有上次序列。

注意:

next_permutation()和prev_permutation()在头文件<algorithm>下。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值