C++:algorithm常用函数

C++网址:www.clpusplus.com

algorithm是C++一个常用的头文件,译为“算法”,其中有几个常用库函数。

#include
#include
using namespace std;
int main(){

    return 0;
}

1、sort(排序)

sort一般用于结构体数组排序

格式:

default (1)	
template 
  void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)	
template 
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

例:

#include
#include
using namespace std;
int a[15],n;
bool cmp(int a,int b){
    return a>b;
}
int main(){
    cin>>n;
    for(int i=0;i>a[i];
    sort(a,a+n,cmp);//cmp:排序顺序,不写则默认升序
    for(int i=0;i

输入:

5

1 2 3 4 5

输出:

5 4 3 2 1

2、max/min(最大值/最小值)

max/min是求最大值/最小值的函数

格式:

max:
default (1)	
template  const T& max (const T& a, const T& b);
custom (2)	
template 
  const T& max (const T& a, const T& b, Compare comp);
min:
default (1)	
template  const T& min (const T& a, const T& b);
custom (2)	
template 
  const T& min (const T& a, const T& b, Compare comp);

注意:max/min只能传两参数!!!

例1:2参数

#include
#include
using namespace std;
int a,b;
int main(){
    cin>>a>>b;
    cout<

输入:

1 7

输出:

7

1

例2:3参数

#include
#include
using namespace std;
int a,b;
int main(){
    cin>>a>>b;
    cout<

输入:

1 2 3

输出:

3

1

3、swap(交换函数)

冒泡排序中可以用到,或者三变量法。

三变量法:

#include
#include
using namespace std;
int a,b,t;
int main(){
    cin>>a>>b;
    t=a;
    a=b;
    b=t;
    cout<

输入:

1 2

输出:

2 1

格式:

// defined in  before C++11
template  void swap (T& a, T& b);

例1:

#include
#include
using namespace std;
int a,b;
int main(){
    cin>>a>>b;
    swap(a,b);
    cout<

输入:

2 3

输出:

3 2

例二:冒泡排序

#include
#include
using namespace std;
int n,a[100005];
int main(){
    cin>>n;
    for(int i=0;i>a[i];
    for(int i=0;ia[j+1])
                swap(a[j+1],a[j]);
    for(int i=0;i

输入:

5

1 7 2 4 8

输出:

1 2 4 7 8

最后,请大家一键三连

C++:algorithm常用函数_第1张图片

你可能感兴趣的:(c++,算法)