[C++]头文件

时间:2022-03-29 16:18:43

本博文仅示例一些常用的函数:

  sort、for_each、

1. sort

/*
STL - <algorithm> - sort
template< class RandomIt, class Compare >
  void sort( RandomIt first, RandomIt last, Compare comp );
Eg:sort(array,array+10,bool cmpFunc)
template< class RandomIt >
  void sort( RandomIt first, RandomIt last );
Eg:sort(vector.begin(),vector.end(),bool cmpFunc)
*/
#include <algorithm>
#include <iostream>
using namespace std; bool com(int a,int b) {
// return a>b; //降序
return a<b;//升序
} int main(){
int a[10]={9,6,3,8,5,2,7,4,1,0};
for(int i=0;i<10;i++)
cout<<a[i]<<"\t";
cout<<endl;
sort(a,a+10,com);//com函数作为可选(自定义)的传入参数
for(int i=0;i<10;i++)
cout<<a[i]<<"\t";
return 0;
}
/*
9 6 3 8 5 2 7 4 1 0
0 1 2 3 4 5 6 7 8 9
*/

2.for_each

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std; template<class T>
struct plus2
{
void operator()(T&x)const
{
x+=2;
} }; void printElem(int& elem)
{
cout << elem << endl;
} int main()
{
int ia[]={0,1,2,3,4,5,6};
for_each(ia,ia+7,printElem);//输出 int ib[]={7,8,9,10,11,12,13};
vector<int> iv(ib,ib+7);
for_each(iv.begin(),iv.end(),plus2<int>());//更改元素
for_each(iv.begin(),iv.end(),printElem);//输出
return 0;
}

 

3.其他常用函数

  移步:[头文件algorithm中的常用函数](https://www.cnblogs.com/TWS-YIFEI/p/5813256.html)