如何在C ++ 03中用自定义谓词调用std :: unique?

问题描述 投票:0回答:1

我在C ++ 11中看到了如何执行此示例:

std::unique(v.begin(), v.end(), [](float l, float r)
{ 
  return std::abs(l - r) < 0.01; 
});

但是,这对我来说在C ++ 03中失败:

error: template argument for 'template<class _FIter, class _BinaryPredicate> _FIter std::unique(_FIter, _FIter, _BinaryPredicate)' uses local type 'CRayTracer::myFunc()::<lambda(float, float)>'

如何在C ++ 03中做到这一点?我认为Lambda可能已经存在,并且函子/函数对象已经存在,对吗?只是寻找一个简单的解决方案,并不需要是可扩展的-它只会在这里使用。

c++ lambda functor c++03
1个回答
0
投票

Lambda已在C ++ 11中引入。

关于正式的正确表达方式,我引荐您参考其他参考文献,草率地说

auto f = [](float l, float r){ 
  return std::abs(l - r) < 0.01; 
};
f(0.1,0.2);

等于

struct unnamed {
    float operator()(float l, float r){
        return std::abs(l - r) < 0.01; 
    }
};
unnamed f;
f(0.1,0.2);

即您可以随时用手写函子类替换lambda。创建函子的实例,然后传递它而不是lambda。

© www.soinside.com 2019 - 2024. All rights reserved.