C++头文件 <algorithm>的 常用函数(详细)

1.sort( ) 用于排序,默认从小到大排。

2.max( ):两数最大

3.min():两数最小

4.abs():求一个数的绝对值   (  与<cmath>中的fbs(),不同,因abs()只用于整型变量 )

5.swap(): 交换 x 与 y 的值

6.reverse(): 反转数组函数  
(1)翻转整个数组 
 例:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int a[5]={11,22,33,44,55};
    reverse(a,a+5);
    for(int i =0;i<5;i++)
    {
        cout << a[i] << " ";
    }
    return 0;
 }

输出 55 44 33 22 11 

(2)翻转部分数组
 

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int a[5]={11,22,33,44,55};
    reverse(a+3,a+5);
    for(int i =0;i<5;i++)
    {
        cout << a[i] << " ";
    }
    return 0;
 }

输出:11 22 33 55 44


7.fill():在某区间内填充某个值(适用于所有类型的数组,容器)

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int a[5]={11,22,33};
    fill(a+3,a+5,9999);
    for(int i=0;i<5;i++)
    {
        cout << a[i] << " ";
    }
    return 0;
}

输出 : 11 22 33 9999 9999

8.count() : 在数组中查找 x 在某区间出现的次数

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int a[5]={11,22,33,44,44};
    cout << count(a,a+5,44);        //在使用时要写出 地址的 范围
    return 0;
}

输出 : 2


9.__gcd( ):  求两数的最大公因数     //注意:如果想求最大公倍数 = 两数相乘 /  最大公因数;

#include <iostream>
#include <algorithm>
using namespace std;
int main()                                            
{
    int a=12,b=4;
    int Gcd=__gcd(a,b);
    cout << Gcd; 
    return 0;
}

输出 : 4

10. next_permutation( ):给定的数组容器全排列。

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int a[3]={1,2,3};
    do{
        cout << a[0] <<a[1] << a[2] << endl;
    }while(next_permutation(a,a+3));              //  给定地址范围
    return 0;
}

输出 :123 132 213 231 312 321


 

  • 28
    点赞
  • 171
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李 吉 脖.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值