Go教程

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

本文主要是介绍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


 

这篇关于C++头文件 <algorithm>的 常用函数(详细)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!