[C++]头文件<algorithm>

本文介绍C++ STL中sort与for_each函数的基本使用方法,包括sort函数的升序与降序排列示例及for_each函数的输出与元素修改应用。此外还提供了指向algorithm头文件中更多常用函数的链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

  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) 

转载于:https://www.cnblogs.com/johnnyzen/p/9095708.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值