zoukankan      html  css  js  c++  java
  • algorithm头文件(sort 函数)

    头文件

    #include<algorithm>

    用法:

    1. max

    2. min

    3. abs(只能取整型的绝对值)

    4. sort排序,复杂度:n*log(n)

    1. 首先是升序排序

    sort(a,a+n);//对a到a+n-1这n个元素进行默认的升序排序

    2. 然后是定义一个比较函数实现降序排序

    1. 对数组
    bool cmp1(int a,int b)
    {
       return a>b;//降序排列
       //return a<b;//升序
    }
    sort(a,a+n,cmp1);
    
    1. 对结构体struct

    第一种:定义比较函数

    struct person{
      int id;
      char name[10];
      };
    person man[10];
    bool cmp(person a,person b)
    {
      return a.id>b.id;//降序
       //return a.id<b.id;//升序
    }
    sort(man,man+10,cmp);
    

    第二种:重载运算符

    struct person{
      int id;
      char name[10];
    bool operator<(const person& s)
    {
       return id>s.id;//降序
        //return id<s.id;//升序}
      };
    person man[10];
    sort(man,man+10);
    

    5. swap交换两个数的值

    6. reverse翻转数组的值

    reverse(a,a+10);

    7. find 查找一个数的地址

    int *p=find(a,a+10,2);//找到了p就是2的地址,没找到p就是数组结尾

    8. 填充函数:fill() 在区间内填充某一个值。

    fill(a,a+10,2)//对a到a+n-1这n个元素赋值2

    9. count 查找出现的次数

    int p=count(a, a+10, 2);

    10. 求最大公因数:__gcd()

    int p= __gcd(a,b);

    11. 求交集、并集、差集:set_intersection()、set_union()、set_difference()

    12. 全排列:next_permutation()

    int a[3] = {1,2,3};
    	do{
    		cout<<a[0]<<a[1]<<a[2]<<endl; 
    	}while(next_permutation(a,a+3));	//输出1、2、3的全排列 
    
  • 相关阅读:
    页面制作 Chapter 3--HTML
    页面制作 Chapter 2--开发、调试工具
    页面制作 Chapter 1--PhotoShop切图笔记
    打开AzureRay园子的大门,欢迎大家串门哟~
    自定义Console.log
    简单事件模型,JS防止单个函数异步重复调用
    C# 调用Restful 请求
    各类开源License说明
    面试JS
    gitignore
  • 原文地址:https://www.cnblogs.com/yzmy/p/13945350.html
Copyright © 2011-2022 走看看