find(),find_if(),以及巧妙的函数对象,函数适配器

在学习到《Essential C++》3.6节时自己按照自己的想法来实现书上提到的思路。代码虽然简单,不过自己却发现有很多其他地方不熟悉,比如函数指针的用法,仿函数和函数适配器的使用。捣鼓了半天,总算懂了点眉目,简单总结下以备忘。

文档按照五部分分写,先依次简单地介绍find()与find_if()算法、函数指针用法、仿函数(functon object)和函数适配器(function adapters)。最后贴上自己实验的代码并简单分析。

一、
因为问题起于泛型搜索算法find_if(),所以先总结下有关find()和find_if()。 声明:
        InputIterator
        find (InputIterator beg, InputIterator end, const T& value)
        InputIterator
        find_if(InputIterator beg, InputIterator end, UnaryPredicate op)第一种形式返回在搜索域[beg,end)内与value值相等的元素的地址;
第二种形式返回在搜索域[beg,end)内满足一元谓词函数op(elem)为真的元素的地址。
     1) 以上两种形式在搜索不到匹配元素的情况下均返回end;
     2) 注意op函数调用期间不能够改变自身的状态;
     3) op不能更改传递进来的参数;

二、
为了增强泛型算法的灵活性,一些泛型算法允许传递用户自定的的函数。泛型算法在使用辅助函数时有不同的方式,有些是可以省略的,即算法是可以不用给定的函数,而有些是强制性的,即必须使用这些函数。如下         
// CODE SNIPPET
        void print (int elem)
        {         
                cout <<elem <<’ ‘;
        }
        ……
        for_each (coll.begin(), coll.end(), print);一种特殊的辅助函数便是谓词函数,谓词函数通常指的是返回值为boolean的函数,它们通常用来为排序或者搜索算法指定参照条件。在使用中谓词函数可分为带有一个参数的谓词函数(unary)和需要两个参数的谓词函数(binary),值得注意的是并不是所有返回值为boolean类型的函数都是合法的谓词函数。

三、
仿函数是一种对象,但它具有函数一样的功能,并且比函数更有优势。其中一点便是效率更高。我们使用的仿函数通常被声明为inline,所以其大部分执行逻辑在编译时已经基本确定,因而少掉了频繁调用函数的开销。可以自己定义简单的仿函数,如下: // CODE SNIPPET
class Print{
        public:
                void operator() (int elem) const
                {
                        cout <<elem <<’ ‘;
                 }
};
……
for_each (coll.begin(), coll.end(), Print());
……C++的STL中提供了多种预定义的仿函数,如negate<type>(), plus<type>(), minus<type>(), multiplies<type>(), divides<type>(), modulus<type>(), equal_to<type>(), not_equal_to<type>(), less<type>(), greater<type>(), less_equal<type>(), greater_equal<type>(), logical_not<type>(), logical_and<type>(), logical_or<type>().

四、
函数适配器也是一种仿函数,不过这种仿函数更为高等,因为它可以将一个仿函数与另一个仿函数/ 值/ 特殊的函数结合起来。

不难发现,STL常使用的仿函数虽然提供了多种有用的仿函数,然而这些仿函数均是通过迭代器对容器里面的元素进行操作,但是有时候你还需要用其他的值结合,这时候便可以使用函数适配器(见下面的例子)。

编译不能通过的代码如下所示: // code snippet
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

bool less_than(int a, int b)
{
        return (a<b ? true:false);
}

vector<int> filter(const vector<int> &vec, int filter_value, bool (*ptr_func)(int, int))
{
        vector<int> temp;
        vector<int>::const_iterator iter = vec.begin();

        while (find_if(iter, vec.end(), ptr_func(*iter, filter_value)) != vec.end())
        {
                temp.push_back(*iter);
                ++iter;
        }        
        return temp;
}

void display(vector<int> &vec)
{
        for (int ix=0; ix<vec.size(); ++ix)
                cout <<vec[ix] <<" ";
        cout <<"\n";
}
        
int main()
{
        const int nsize = 5;
        int int_arr[nsize] = { 2, 4, 5, 6, 7};
        vector<int>vec(int_arr, int_arr+nsize);
        display(vec);
        vector<int>result;

        result = filter(vec, 6, less_than);
        display(result);
        
        return 0;        
}可见,我在使用find_if()函数的时候,将里面本应该为“函数指针”的第三个参数写成了对这个函数的“函数调用”,这是不允许的。但整个程序的思路并没有错,因为上面的代码可以通过仿函数来解决的。

上面也提到,一般通用的仿函数仅是对容器里面的值进行处理,但本例的思路是需要将容器里面的每个值以此与另一个值val进行比较的。所以必须要使用到函数适配器来将一个仿函数与一个值进行绑定。如下是更正后的代码: // code snippet
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

bool less_than(int a, int b)
{
        return (a<b ? true:false);
}

vector<int> filter(const vector<int> &vec, int val, less<int>&lt)
{
        vector<int> nvec;
        vector<int>::const_iterator iter = vec.begin();
        
        while ((iter=find_if(iter, vec.end(), bind2nd(lt, val))) != vec.end())
        {
                nvec.push_back(*iter);
                iter ++;
        }
        return nvec;
}

void display(vector<int> &vec)
{
        for (int ix=0; ix<vec.size(); ++ix)
                cout <<vec[ix] <<" ";
        cout <<"\n";
}
        
int main()
{
        const int nsize = 5;
        int int_arr[nsize] = { 2, 4, 5, 6, 7};
        vector<int>vec(int_arr, int_arr+nsize);
        display(vec);
        vector<int>result;

        result = filter(vec, 6, less<int>());
        display(result);
        
        return 0;        
}

原文链接: https://www.cnblogs.com/wengzilin/archive/2012/10/20/2732252.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    find(),find_if(),以及巧妙的函数对象,函数适配器

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/66467

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午12:21
下一篇 2023年2月9日 下午12:21

相关推荐