11

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?

zenzelezz
  • 813
  • 2
  • 10
  • 26
user855
  • 19,048
  • 38
  • 98
  • 162
  • 1
    Vaguely related: the closest non-`map`-specific thing to `std::map::find` is arguably [`std::binary_search`](http://en.cppreference.com/w/cpp/algorithm/binary_search), which seeks the value in a pre-sorted random-access container (e.g. `vector`, array, `deque`). – Tony Delroy May 28 '15 at 03:21
  • @TonyD I think you mean `std::lower_bound`. `binary_search` doesn't return an iterator. – Mark Ransom May 28 '15 at 04:08
  • @MarkRansom: well, when calling `mymap.find(x)` for a `!= mymap.end()` membership test (which is a more trivial but very common use, though arguably best replaced with `mymap.count()`), `binary_search` is more similar, while when you're interested in the position of a match `lower_bound`'s needed (with a check that you're not at a greater-than-wanted key). – Tony Delroy May 28 '15 at 09:28

1 Answers1

13

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.

vsoftco
  • 55,410
  • 12
  • 139
  • 252