【STL】非变异算法之循环

9 篇文章 0 订阅

for_each的使用

  1. 实例1
    简单的对数组和容器进行操作
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
/for_each的函数
void printCube(int n)
{
    cout<<n*n*n<<endl;
}
int main()
{
    for_each  数组
    int a[] = {0,1,2,3,4,5,6,7,8,9};
    int len = sizeof(a)/sizeof(int);
    for_each(a,a+10,printCube);
    for_each   容器
    vector<int>iVec1(a,a+10);
    for_each(iVec1.begin(),iVec1.end(),printCube);
    system("pause");
    return 0;
}
  1. 实例2
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class printInfo打印类  最大值  最小值  和
{
private:
    int nSum;
    int nMax;
    int nMin;
    int count;
public:
    printInfo():count(0),nSum(0){}
    int getnSum(){return nSum;}
    int getnMax(){return nMax;}
    int getnMin(){return nMin;}
    void operator() (int x)
    {
        if(count == 0)
        {
            nMax = x;
            nMin = x;
        }
        else
        {
            if(nMin > x)
                nMin = x;
            if(nMax < x)
                nMax = x;
        }
        count++;
        nSum += x;
    }
};
int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9};
    int len = sizeof(a)/sizeof(a[0]);
    printInfo P = for_each(a,a+len,printInfo());
    cout<<"最大值:"<<P.getnMax()<<endl;
    cout<<"最小值:"<<P.getnMin()<<endl;
    cout<<"和:"<<P.getnSum()<<endl;
    system("pause");
    return 0;
}

3.实例3

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
打印类  最大值  最小值  和
template<class T,class T1>
class printInfo:public unary_function<T,T1>
{
private:
    T nSum;
    T nMax;
    T nMin;
    int count;
public:
    printInfo():count(0),nSum(0){}
    T getnSum(){return nSum;}
    T getnMax(){return nMax;}
    T getnMin(){return nMin;}
    T1 operator() (T x)
    {
        if(count == 0)
        {
            nMax = x;
            nMin = x;
        }
        else
        {
            if(nMin > x)
                nMin = x;
            if(nMax < x)
                nMax = x;
        }
        count++;
        nSum += x;
    }
};
int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9};
    int len = sizeof(a)/sizeof(a[0]);
    printInfo<int,void> P = for_each(a,a+len,printInfo<int,void>());
    cout<<"最大值:"<<P.getnMax()<<endl;
    cout<<"最小值:"<<P.getnMin()<<endl;
    cout<<"和:"<<P.getnSum()<<endl;
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值