Reputation: 2960
We have C++ map<double, class_name>
mymap
.
We are given some double X
.
Task is to find value in mymap associated with the largest key that is less than equal to X
. If X
is less than lowest key of mymap
return some default value declared before.
My approach is iterate through mymap
and find maximal key that is less than or equal to X
double max = std::numeric_limits<double>::lowest();
for ( auto ii=mymap.begin(); ii!=mymap.end(); ++ii ) {
if (
(*ii).first <= value &&
(*ii).first > max
) {
max = (*ii).first;
}
}
if ( max==std::numeric_limits<double>::lowest() )
return defaultValue;
return colorset.find(max)->second;
Is this correct approach? I am new at c++ map, so I want to know may be there is a better way of implementing this task?
I guess proposed algorithm's complexity is O(n)
, probably there is a way to find it O(log n)
or with even better complexity or memory allocation?
Upvotes: 1
Views: 549
Reputation: 726619
You can use map::lower_bound
to find the smallest element larger than or equal to X
, check if you've got a begin()
iterator to decide that the value is smaller than the smallest one in the map, and go back one step to go to the key that's the largest one not exceeding X
:
map<double, class_name>::const_iterator iter = mymap.lower_bound(X);
if (iter->first == X || iter != mymap.begin()) {
if (iter->first != X) --iter;
cerr << iter->second << endl;
} else {
cerr << "<default>" << endl;
}
Unlike a plain loop (that iterates all the keys in order) map::lower_bound
knows about the internal structure of std::map
an can take advantage of it during the search, resulting in better performance.
Upvotes: 7