STL之容器、迭代器、算法、仿函数

1、仿函数

    系统已有的:
    greater
    less
    
    系统已有,但比较特殊:
    可以调用自己的成员函数    mem_fun_ref-------参数是: &成员函数名   如:,mem_fun_ref(&CStudent::print_student)
                              注意:print_student函数必须要有返回值----是语法这么要求的
                              好处:直接可以使用 成员函数了,而不用自定义 回调函数
                              经常和 for_each算法 搭配使用
    
    自定义的:
    对象函数-----   注意:好记----赋值函数   第5大成员函数
    
    
容器------数组

利用迭代器、算法 来实现 数组 的 排序、查找
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <list>
#include "Student.h"
using namespace std;

int main()
{
    int array1[]={4,2,7,5,8,1};
    //sort(array1,array1+6,less<int>());
    int *p2=find(array1,array1+6,8);   //注意:find函数的第2个参数,要求是 最后1个元素的下一个的地址,因此加了6
    if(p2!=array1+6)                    //如果p2走到了array1+6,则说明没有找到
    {
        cout<<"找到了:"<<(*p2)<<endl;
    }
    for(int *p=array1;p!=array1+6;p++)    //这是采用迭代器法 遍历元素的思想写的代码;我们原来不这么用!
    {
        cout<<(*p)<<"\t";
    }
    cout<<endl;
    

    return 0;

    
    
一个常用的仿函数:----mem_fun_ref

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <list>
#include "Student.h"
using namespace std;


void print(CStudent &other)
{
    other.print_student();
    return;
}


int main()
{
    CStudent stu1(1003,"zhangsan");
    CStudent stu2(1001,"lisi");
    CStudent stu3(1002,"wangwu");
    vector<CStudent> vec1;
    vec1.push_back(stu1);
    vec1.push_back(stu2);
    vec1.push_back(stu3);

    //for_each(vec1.begin(),vec1.end(),print);
    for_each(vec1.begin(),vec1.end(),mem_fun_ref(&CStudent::print_student));
    
    return 0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bryan Ding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值