二进制搜索std:map

binary search a std:map

本文关键字:map std 搜索 二进制      更新时间:2023-10-16

使用c++,如果我在std::map中有n整数,是否可以有效地搜索std::map中小于k的最大元素?

例如,我有{1, 3, 5, 6},而k是4返回的值应该是3

我知道std::map可以在log(n)中搜索,如果它完全匹配的话。

使用lower_bound并将返回的迭代器递减一。

您可以使用方法lower_bound。例如

#include <iostream>
#include <map>
int main() 
{
    std::map<int, int> m = { { 1, 0 }, { 3, 0 }, { 5, 0 }, { 6, 0 } };
    auto it = m.lower_bound( 4 );
    if ( it != m.begin() )
    {
        std::cout << ( --it )->first << std::endl;
    }
    return 0;
}

查看std::map::lower_bound()。请注意,如果有匹配项,它将返回一个完全匹配项。std::set也有这种情况。

相关文章: