简体   繁体   中英

finding maximal element in c++ map

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?

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.

Here is a demo on ideone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM