Are std::find and std::map.find both O(logN)?

空扰寡人 提交于 2020-01-23 05:55:22

问题


Are std::find and std::map.find both O(logN)? If they are, how does std::find implement search over std::map in logarithmic time?

Is the implementation of std::find specialized for the std::map use case?


回答1:


No, std::find is O(N), regardless of the container. It doesn't know the "container", there is no specialization for std::map. std::find uses only the iterators, which do not have information about the underlying container. According to cppreference.com, the implementation is equivalent to:

template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value)
{
    for (; first != last; ++first) {
        if (*first == value) {
            return first;
        }
    }
    return last;
}

According to the C++ standard (emphasize mine):

25.2.5 Find [alg.find]

template<class InputIterator, class T>
  InputIterator find(InputIterator first, InputIterator last,
                     const T& value);
...
  1. Returns: The first iterator i in the range [first,last) for which the following corresponding conditions hold: *i == value, . . . . Returns last if no such iterator is found.

  2. Complexity: At most last - first applications of the corresponding predicate.



来源:https://stackoverflow.com/questions/30496499/are-stdfind-and-stdmap-find-both-ologn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!