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

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

本文关键字:find std logN map and Are both      更新时间:2023-10-16

std::findstd::map.find都是O(logN(吗?如果是,std::find如何在对数时间内实现对std::map的搜索?

std::find的实现是否专门用于std::map用例?

否,std::find是O(N(,与容器无关。它不知道"容器",std::map没有专门化。std::find只使用迭代器,迭代器没有关于底层容器的信息。根据cppreference.com,该实现等效于:

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;
}

根据C++标准(强调矿(:

25.2.5查找[alg.Find]

template<class InputIterator, class T>
  InputIterator find(InputIterator first, InputIterator last,
                     const T& value);
...
  1. 返回:范围[first,last)中的第一个迭代器i,它符合以下相应条件:*i == value。如果未找到此类迭代器,则返回last

  2. 复杂性:最多对应谓词的倒数第一个应用程序