Reputation: 1208
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
?
For example I have {1, 3, 5, 6}
and k
is 4
the returned value should be 3
I know std::map
can search in log(n)
, if the it is exact match.
Upvotes: 1
Views: 449
Reputation: 310950
You can use method 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;
}
Upvotes: 3
Reputation: 62063
Look into std::map::lower_bound()
. Note that it will return an exact match if there is one. std::set
has this as well.
Upvotes: 2
Reputation: 126787
Use lower_bound
and decrement the returned iterator by one.
Upvotes: 5