Using a functor in find_if [closed]

那年仲夏 提交于 2019-12-11 22:59:25

问题


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.

Here's my 'equal' functor:

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 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)

and some other stuff.

THanks in advance!


回答1:


  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
{
   ...
};

and

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


来源:https://stackoverflow.com/questions/49677455/using-a-functor-in-find-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!