Why does the standard library have find and find_if?

前端 未结 4 975
挽巷
挽巷 2021-01-11 16:06

Couldn\'t find_if just be an overload of find? That\'s how std::binary_search and friends do it...

4条回答
  •  醉话见心
    2021-01-11 16:57

    A predicate is a valid thing to find, so you could arrive at ambiguities.


    Consider find_if is renamed find, then you have:

    template 
    InputIterator find(InputIterator first, InputIterator last, const T& value);
    
    template 
    InputIterator find(InputIterator first, InputIterator last, Predicate pred);
    

    What shall be done, then, with:

    find(c.begin(), c.end(), x); // am I finding x, or using x to find?
    

    Rather than try to come up with some convoluted solution to differentiate based on x (which can't always be done*), it's easier just to separate them.

    *This would be ambiguous, no matter what your scheme is or how powerful it might be†:

    struct foo
    {
        template 
        bool operator()(const T&);
    };
    
    bool operator==(const foo&, const foo&);
    
    std::vector v = /* ... */;
    foo f = /* ... */; 
    
    // f can be used both as a value and as a predicate
    find(v.begin(), v.end(), f); 
    

    †Save mind reading.

提交回复
热议问题