二进制搜索std:map

时间:2014-05-31 13:46:24

标签: c++ search std

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

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

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

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:3)

您可以使用方法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;
}

答案 2 :(得分:2)

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