[C++]头文件<algorithm>
2024-08-27 02:10:17
本博文仅示例一些常用的函数:
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)
最新文章
- 在linux下Ant的环境配置
- MySQL Cluster搭建与测试
- 重新想象 Windows 8 Store Apps (62) - 通信: Socket TCP, Socket UDP
- commonJS规范基本机构
- svg绘制蓝色星空,月亮,旋转灯塔
- mvc4 to mvc5 and EF5 to EF6
- 数据分析:Weka,Matlab,R,SPSS,SAS等分析软件的入门
- 关于git的一些常用命令
- PC-HTML5-搜索框
- thinkphp批量删除的实现
- VS2015智能提示由英文改为中文
- pat1091-1100
- [CSDN_Markdown]使用LaTeX基本数学公式
- Flutter之内置动画(转)
- HARD FAULT
- [转]vs2010用 boost.python 编译c++类库 供python调用
- linux调度器源码分析 - 新进程加入(三)
- Linux 对文件进行加密存放
- SQL 提高性能
- 堆排序之Java实现