在find_if中使用函子 [英] Using a functor in find_if

查看:155
本文介绍了在find_if中使用函子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用模板函子作为find_if的参数.我不确定语法.

I was wondering how would I use a template functor as an argument for find_if. I'm not sure about the syntax.

例如,假设一个函子从一个产品的多重映射中删除一个产品.为此,我必须扫描"多图,找到产品(使用同等的仿函数)然后将其删除.

For example, suppose a functor that deletes a product from a multimap of products. To do that, I have to "scan" the multimap, find the product (using my equal functor) and delete it.

这是我的相等"函子:

class isEqual
{
public:
    isEqual(T* t) : t_(t) {}

    bool operator()(const pair<int, T*> pair) const
    {
        return (pair.second == t_);
    }

private:
    T* t_;
};

这是被称为擦除产品"的函子,在这里我必须使用等于"产品:

and Here's the functor that's called "erase product" where I have to use my 'is equal' product:

class EraseProduct
public:
    EraseProduct(multimap <int, Produit*>& multimap) : multimap_(multimap) {} ; // constructor that initializes 'multimap_' attribute

    multimap <int, Product*>& operator()(Product* product)
    {
         auto it = find_if(multimap_.begin(), multimap_.end(), USE_EQUAL_FUNCTOR_HERE)

         if (it != multimap_.end)
         multimap_.erase(it)

         return multimap_;

    }
private:
    multimap<int, Product*>& multimap_;

Product 是一个类.所以我的问题是关于我在哪里写了"USE_EQUAL_FUNCTOR_HERE".我找不到正确的语法.我试过了:

Product is a class. So my question is about where I wrote "USE_EQUAL_FUNCTOR_HERE". I can't figure out the correct syntax. I tried:

IsEqual(), IsEqual(product)

和其他一些东西.

提前致谢!

推荐答案

  1. 首先,您必须将isEqual设为类模板.如前所述,不是.
  2. 然后,您将使用Product作为模板参数来创建实例,并将其用作find_if的参数.
  1. First you have to make isEqual a class template. As posted, it is not.
  2. Then, you would use Product as the template parameter to create an instance and use it as an argument to find_if.


template <typename T>
class isEqual
{
   ...
};

auto it = find_if(multimap_.begin(), multimap_.end(), isEqual<Product>());

这篇关于在find_if中使用函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆