问题
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:
- First you have to make
isEqual
a class template. As posted, it is not. - Then, you would use
Product
as the template parameter to create an instance and use it as an argument tofind_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