[英]binary search a std:map
Using c++, if I have n
integers in a std::map
, is it possible to efficiently search the largest element that is smaller than k
in std::map
? 使用c ++,如果我在std::map
具有n
整数,是否可以有效地搜索std::map
小于k
的最大元素?
For example I have {1, 3, 5, 6}
and k
is 4 the returned value should be 3 例如我有{1, 3, 5, 6}
并且k
为4,则返回值应为3
I know std::map
can search in log(n)
, if the it is exact match. 我知道std::map
可以在log(n)
搜索,如果它完全匹配。
使用lower_bound
并将返回的迭代器减一。
You can use method lower_bound
. 您可以使用lower_bound
方法。 For example 例如
#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;
}
Look into std::map::lower_bound()
. 查看std::map::lower_bound()
。 Note that it will return an exact match if there is one. 请注意,如果存在匹配项,它将返回完全匹配项。 std::set
has this as well. std::set
也有这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.