Finding minimum value in a Map

Posted by Sunny on Stack Overflow See other posts from Stack Overflow or by Sunny
Published on 2010-04-17T17:11:21Z Indexed on 2010/04/17 17:23 UTC
Read the original article Hit count: 144

Filed under:
|
|

I have a map and I want to find the minimum value (right hand side) in the map. Right now here is how I did it

bool compare(std::pair<std::string ,int> i, pair<std::string, int> j) {
  return i.second < j.second;
}
////////////////////////////////////////////////////
std::map<std::string, int> mymap;

mymap["key1"] = 50;
mymap["key2"] = 20;
mymap["key3"] = 100;

std::pair<char, int> min = *min_element(mymap.begin(), mymap.end(), compare); 
std::cout << "min " << min.second<< " " << std::endl;

This works fine and I'm able to get the minimum value the problem is when I put this code inside my class it doesn't seem to work

int MyClass::getMin(std::map<std::string, int> mymap) {
  std::pair<std::string, int> min = *min_element(mymap.begin(), mymap.end(), 
                                                 (*this).compare);
                                                 //error probably due to this

  return min.second; 
}

bool MyClass::compare(
    std::pair<std::string, int> i, std::pair<std::string, int> j) { 
  return i.second < j.second; 
}

Also is there a better solution not involving to writing the additional compare function

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl