C++ for_each高级用法


主要参考:for_each的用法,转载自蕭鴻森的blog
(找不到原文的链接)

在接触C++特性Lambda时,接触到for_each,没想到这内容还挺多的,所以,先了解for_each,再学习Lambda。
这些文章其实都是在网上参考前人的博客,有些自己整理,有些不需要修改,本意是为自己学习,以备以后查阅之用。如有侵权,联系我即可。
本文代码大部分自己写过,使用MinGW。
原文非常好,建议阅读原文。这里仅摘用重要的内容

引入

先看一段不用for_each 的代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    int a[] = { 1, 2, 3, 4};
    vector<int> v(a, a+sizeof(a)/sizeof(int));
    for(vector<int>::iterator itor = v.begin();itor!=v.end();++itor)
    {
        cout<<*itor<<endl;
    }
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

其中这句代码:

    for(vector<int>::iterator itor = v.begin();itor!=v.end();++itor)
   
   
  • 1

略长,如果不常写,倒是很容易手生。

使用for_each代码就比较简洁。
for_each()事实上是個function template,其实质如下[effective STL item 41]

template<typename InputIterator, typename Function>
Function for_each(InputIterator beg, InputIterator end, Function f) {
  while(beg != end) 
    f(*beg++);
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

由以上source可知,for_each()只能配合global function和function object。

以下将对procedure based、object oriented、generics三种paradigm与for_each()搭配做探讨。

Procedure Based与for_each()搭配

1、不传入参数

void fun(int i )
{
    cout<<i<<endl;
}

int main()
{
    int a[] = { 1, 2, 3, 4};
    vector<int> v(a, a+sizeof(a)/sizeof(int));
    for_each(v.begin(), v.end(), fun);
}

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2、传入参数

要传入参数给global function ,需要使用 ptr_fun() 这个 function adapter 将global function 转成function object , 然后再用bind2nd() 将参数bind成一个function object。(这句话好拗口)。

void fun(int i, const char* str)
{
    cout<<str<<i<<endl;
}

int main()
{
    int a[] = { 1, 2, 3, 4};
    vector<int> v(a, a+sizeof(a)/sizeof(int));
    for_each(v.begin(), v.end(), bind2nd(ptr_fun(fun), "Element:"));
}

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

bind2nd 和 ptr_fun看这里
bind1st bind2nd的使用
【STL】ptr_fun详解

Object Oriented 与for_each 搭配

1、不传入参数,使用function object

#include<iostream>
#include<vector>
#include<algorithm>
#include<typeinfo>
using namespace std;

struct Play
{
    void operator () (int i)
    {
        cout<<i<<endl;
    }
};

int main()
{
    int a[] = { 1, 3, 4, 5};
    vector<int> vc(a, a+sizeof(a)/sizeof(int));
    for_each(vc.begin(), vc.end(), Play());
}

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

输出是

1
3
4
5

这里我有一点疑问, Play() 是怎么用的?
我给代码加了一点输入,查看建立和销毁对象的过程:

#include<iostream>
#include<vector>
#include<algorithm>
#include<typeinfo>
using namespace std;

struct Play
{
    Play()
    {
        cout<<"new a Play"<<endl;
    }
    Play(const Play&)
    {
        cout<<"new a copy Play"<<endl;
    }
    void operator () (int i)
    {
        cout<<i<<endl;
    }
    ~Play()
    {
        cout<<"dispose a Play"<<endl;
    }
};

int main()
{
    int a[] = { 1, 3, 4, 5};
    vector<int> vc(a, a+sizeof(a)/sizeof(int));
    for_each(vc.begin(), vc.end(), Play());
    cout<<"See something"<<endl;
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

此时输出是:

new a Play
1
3
4
5
new a copy Play
dispose a Play
dispose a Play
See something

可以看到这个过程有两个Play对象生成,但是,用于输出元素的却是第一个对象(重载() 操作符),为什么?
这时候回去看for_each的源码,就会发现,它的返回值是function,以我的猜测,应该是这样的。Play() 生成一个临时的匿名的Play对象,传入for_each 函数里,然后执行完for_each 函数后,return一个function时,Play用复制构造函数生成一个Play对象,然后两个Play对象的生命周期都结束,于是依次销毁。

2、传入参数

可以通过构造函数的技巧传入参数

#include<iostream>
#include<vector>
#include<algorithm>
#include<typeinfo>
using namespace std;

struct Play
{
    const char* str;
    Play(const char* s):str(s) {}
    void operator () (int i)
    {
        cout<<str<<i<<endl;
    }
};

int main()
{
    int a[] = { 1, 3, 4, 5};
    vector<int> vc(a, a+sizeof(a)/sizeof(int));
    for_each(vc.begin(), vc.end(), Play("Element:"));
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Member function 与 for_each 搭配

1、不传入参数

通过mem_fun_ref() 这个funtion adapater 将 member funtion 转成 function object。

#include<iostream>
#include<vector>
#include<algorithm>
#include<typeinfo>
using namespace std;

class Door
{
public:
    void open() const
    {
        cout<<"open door horizontally"<<endl;
    }
};

class DoorController
{
protected:
    vector<Door> _doorVec;

public:
    void addDoor(Door door)
    {
        _doorVec.push_back(door);
    }

    void openDoor() const
    {
        for_each(_doorVec.begin(), _doorVec.end(), mem_fun_ref(&Door::open));
    }
};

int main()
{
    DoorController dc;
    dc.addDoor(Door());
    dc.addDoor(Door());
    dc.openDoor();
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

输出:

open door horizontally
open door horizontally

值得注意的是,mem_fun_ref() 用在 object 的 member function。若要搭配多态,vector必须放pointer,也就是得使用object pointer的member function,此时得使用mem_fun()将member function转成function object。

2、传入参数

要使用 bind2nd

#include<iostream>
#include<vector>
#include<algorithm>
#include<typeinfo>
using namespace std;

class AbstractDoor
{
public:
    virtual void open(const char* str) const = 0; //定义纯虚函数

    virtual ~AbstractDoor() {}
};

class HorizontalDoor: public AbstractDoor
{
    public:
    void open(const char* str) const
    {
        cout<<str<<"open door horizontally"<<endl;
    }
};

class VerticalDoor: public AbstractDoor
{
    public:
    void open(const char* str) const
    {
        cout<<str<<"open door vertically"<<endl;
    }

};

class DoorController
{
protected:
    vector<AbstractDoor*> _doorVec;

public:
    void addDoor(AbstractDoor* door)
    {
        _doorVec.push_back(door);
    }

    void openDoor() const
    {
        for_each(_doorVec.begin(), _doorVec.end(), bind2nd(mem_fun(&AbstractDoor::open), "Jhon "));
    }

    ~DoorController() 
    {
        for_each(_doorVec.begin(), _doorVec.end(), [](AbstractDoor* p)
        {
            delete p;
            p = nullptr;
        });
    }
};

int main()
{
    DoorController dc;
    dc.addDoor(new HorizontalDoor());
    dc.addDoor(new VerticalDoor());
    dc.openDoor();
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

这里用到了Lambda,我会另讲
上面用到mem_fun_ref 和 mem_fun ,我不是很明白,参考:
STL中mem_fun和mem_fun_ref的用法

引用一句很重要的用法:

mem_fun_ref的作用和用法跟mem_fun一样,唯一的不同就是:当容器中存放的是对象实体的时候用mem_fun_ref,当容器中存放的是对象的指针的时候用mem_fun。

Generics与for_each()搭配

1. Funtion template

1.1 不传入参数

#include<iostream>
#include<vector>
#include<algorithm>
#include<typeinfo>
using namespace std;

template<typename T>
void play(T elem)
{
    cout<<elem<<endl;
}

int main()
{
    int a[] = {1, 3, 4, 5};
    vector<int> vc(a, a+sizeof(a)/sizeof(int));
    for_each(vc.begin(), vc.end(), play<int>);
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

1.2 传入参数

#include<iostream>
#include<vector>
#include<algorithm>
#include<typeinfo>
using namespace std;

template<typename T, char str>
void play(T elem)
{
    cout<<str<<elem<<endl;
}

int main()
{
    int a[] = {1, 3, 4, 5};
    vector<int> vc(a, a+sizeof(a)/sizeof(int));
    for_each(vc.begin(), vc.end(), play<int, 'a'>);
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

这里无法传入字串或者别的指针的类型。

2. class template

2.1不传入参数

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;

template<typename T>
class Play/*:public unary_function<T, void>*/ //我不懂为什么原文需要这个?
{
    public:
    void operator() (T elem)
    {
        cout<<elem<<endl;
    }
};
int main()
{
    int a[] = {1, 3, 4, 5};
    vector<int> vc(a, a+sizeof(a)/sizeof(int));
    for_each(vc.begin(), vc.end(), Play<int>());
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

2.2 传入参数

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;

template<typename T, typename V>
class Play/*:public unary_function<T, void>*/ //我不懂为什么原文需要这个?
{
    V _str;
    public:
    Play(V str):_str(str) {}
    void operator() (T elem)
    {
        cout<<_str<<elem<<endl;
    }
};
int main()
{
    int a[] = {1, 3, 4, 5};
    vector<int> vc(a, a+sizeof(a)/sizeof(int));
    for_each(vc.begin(), vc.end(), Play<int, const char*>("Element "));
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

END

        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
            </div>
        </article>

猜你喜欢

转载自blog.csdn.net/qq_20330595/article/details/82107738