[杂乱笔记]algorithm头文件下的常用函数

使用algorithm头文件,需要在头文件加using namespace std;
1、常见的函数(max(),min(),abs(),swap())

int x=98;
int y=7;
int z=12;
printf("%d %d\n",max(x,y),min(y,z));///求最小值和最大值
swap(x,y);///交换x,y的值

int r=-1printf("%d\n",abs(r));///求数的绝对值

2、reverse()、next_permutation()、fill()、sort()
(1)reverse(it,it2):可以将数组指针在(it,it2)之间的远足或容器的迭代器在[it,it2)范围内的元素进行反转。

///a为数组
reverse(a,a+4);///反转a[0]~a[3]的元素

///str为字符串数组
reverse(str.begin()+1,str.begin()+5);///反转str[1]~str[4]的元素

(2)next_permutation():给出一个序列在全排列中的下一个序列,按照字典升序的方式生成的排列

int a[10]={1,2,3};
   do{
     printf("%d %d %d\n",a[0],a[1],a[2]);
   }while(next_permutation(a,a+3));
//1 2 3
//1 3 2
//2 1 3
//2 3 1
//3 1 2
//3 2 1

相反地,perv_permutation():按照字典降序的方式生成的排列(运用此函数前,序列要先从大到小排序)

int a[10]={3,2,1};///从大到小排序
    do{
       printf("%d %d %d\n",a[0],a[1],a[2]);
    }while(prev_permutation(a,a+3));

(3)fill():可以把数组或容器中的某一段区间赋为某个相同的值。和memset不同,这里的赋值可以是数组类型对应范围中的任意值。

fill(a,a+3,5);///将a[0]~a[2]均赋值为5

(4)sort():用来排序的函数
(1)基本数据类型的数组排序

///a为数组
sort(a,a+4);///默认升序排序
sort(a,a+4,less<数据类型>());///升序排序
sort(a,a+4,greater<数据类型>())///降序排序

(2)自定义cmp函数排序

#include <algorithm>
#include <iostream>
#include<stdio.h>
using namespace std;
bool cmp(int a,int b){
  return a<b;///从小到大,如果是a>b就是从大到小
}
int main()
{
    int a[4]={3,2,1,7};
    sort(a,a+4,cmp);
    for(int i=0;i<4;i++)
       printf("%d\n",a[i]);
    return 0;
}

(3)结构体数组

struct node{
  int x,y;
}arr[10];
bool cmp(node a,node b){
  return a.x>b.x;///x从大到小排序
}

bool cmp(node a,node b){
   if(a.x!=b.x) return a.x>b.x;
   else return a.y<b.y;///当x相等的情况下
}

(4)容器的排序
在STL标准容器中,只有vector、string、deque是可以使用sort,像set、map这种容器用红黑树实现的,元素本身有序,故不允许使用sort排序。
例如(vector):

bool cmp(int a,int b){
  return a>b;
}
vector<int>a;
sort(a.begin(),a.end(),cmp);

3、lower_bound和upper_bound()
它们都需要用在一个有序数组或容器中。
lower_bound(first,last,val):用来寻找在数组或容器的[first,last)范围内第一个值>=val的元素的位置,如果数组,则返回该位置的指针;如果是容器,则返回该位置的迭代器。
upper_bound(first,last,val):用来寻找在数组或容器的[first,last)范围内第一个值>val的元素的位置,如果数组,则返回该位置的指针;如果是容器,则返回该位置的迭代器。

int a[4]={1,2,3,4};
  int *lowerpos = lower_bound(a+1,a+4,2);///>=1,位置从下标为1开始
  int *upperpos = upper_bound(a+1,a+4,2);///>1也就是在这个范围内于元素不存在,返回位置
  printf("%d %d\n",lowerpos-a,upperpos-a);///1(下标),2(位置)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章