Why does the standard library have find and find_if?

前端 未结 4 960
挽巷
挽巷 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 16:55

    It can't have the same name because there would be an ambiguity. Suppose that we had a find overload instead of find_if. Then suppose:

    // Pseudo-code
    struct finder
    {
        bool operator()(const T&) const { ... }
        bool operator==(const finder& right) const { ... }
    }
    
    std::vector finders;
    
    finder my_finder;
    
    std::find(finders.begin(), finders.end(), my_finder);
    

    The find would have no way to resolve the inconsistency: Should it attempt to find the finder in the container, or use the finder to do the find operation? To solve this problem they created two function names.

提交回复
热议问题