zoukankan      html  css  js  c++  java
  • [C++]头文件<algorithm>

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

      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]<<"	";
    	cout<<endl;
    	sort(a,a+10,com);//com函数作为可选(自定义)的传入参数  
     	for(int i=0;i<10;i++)  
     		cout<<a[i]<<"	";  
     	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) 

  • 相关阅读:
    跨域问题注解解决
    跳出循环到指定位置
    idea model管理
    maven 取本地jar
    注解 元注解
    手动打jar包到maven
    sonar搭建
    jmockit、junit
    注解
    虚拟机指令
  • 原文地址:https://www.cnblogs.com/johnnyzen/p/9095708.html
Copyright © 2011-2022 走看看