Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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?

like image 496
user855 Avatar asked May 28 '15 03:05

user855


People also ask

What is the time complexity of find in map?

The time complexity for searching elements in std::map is O(log n).

Is map Find O 1?

Yes, indeed std::map will be O(log N) and std::unordered_map will have average constant-time complexity and O(N) in the worst case if there are too many hash collisions. Expected O(1) . It is fairly easy to build a degenerate case where it is O(N) .

What is std::map used for?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.


1 Answers

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.

like image 197
vsoftco Avatar answered Oct 21 '22 11:10

vsoftco