如何用STL编写仿函数?

odd*_*din 4 c++ stl composition functor

STL中可能有以下内容:

int count = count_if(v.begin(), v.end(), bind2nd(less<int>(), 3));
Run Code Online (Sandbox Code Playgroud)

这将返回v中小于3的元素数.如何组成一个返回0到3之间元素数的仿函数?我知道boost有一些设施,但纯STL有可能吗?

Chr*_*ica 8

如果你的意思是使用标准库的functor组合工具,那么不,至少在C++ 98中没有.在C++ 11中,您可以使用std::bind任意组合的仿函数:

using std::placeholders;
int count = std::count_if(v.begin(), v.end(), 
                          std::bind(std::logical_and<bool>(), 
                                    std::bind(std::less<int>(), _1, 3), 
                                    std::bind(std::greater<int>(), _1, 0)));
Run Code Online (Sandbox Code Playgroud)

但对于这样一个简单的谓词来说,这并没有真正令人头痛.

如果允许C++ 11特性,那么最简单的方法可能是lambda,不需要复制仿函数组合(你自己):

int count = std::count_if(v.begin(), v.end(), [](int arg) { 
                          return arg > 0 && arg < 3; });
Run Code Online (Sandbox Code Playgroud)

但对于C++ 98,Chubsdad的答案可能是最好的解决方案.


Chu*_*dad 5

这是你问的问题吗?我知道这不是纯粹的STL,但仍然......

struct InRange
{
    InRange(int x, int y) : mx(x), my(y) { }
    bool operator()(int x)
    {
        return (x >= mx) && (x <= my);
    }
    int mx, my;
};

int main() {
    std::vector<int> v;
    v.push_back(13);
    v.push_back(14);
    v.push_back(18);
    v.push_back(3);

    int count = std::count_if(v.begin(), v.end(), InRange(0, 3));
}
Run Code Online (Sandbox Code Playgroud)