Search code examples
c++algorithmstlc++17smart-pointers

How to use std::min_element on map with unique pointer values? (C++)


I have a map with unique pointer values, and want to get a reference to the pair with the smallest value. I'm using the code below to do this, but am getting an error in the line where I call std::min_element. The error message is: no matching function for call to object.... What should I do to fix this?

  using pair_type = std::pair<std::string, std::unique_ptr<int>>;

  std::map<std::string, std::unique_ptr<int>> map;

  map.insert(std::make_pair("a", std::make_unique<int>(1)));
  map.insert(std::make_pair("b", std::make_unique<int>(2)));
  map.insert(std::make_pair("c", std::make_unique<int>(3)));

  pair_type& min_pair = std::min_element(std::begin(map), std::end(map),
                                         [](pair_type &p1, pair_type &p2) {
                                           return *p1.second < *p2.second;
                                         });


Solution

  • std::map's value type is std::pair<const Key, Value>, you can't edit the key whilst it is in the map.

    using map_type = std::map<std::string, std::unique_ptr<int>>;
    
    map_type map;
    
    map.insert(std::make_pair("a", std::make_unique<int>(1)));
    map.insert(std::make_pair("b", std::make_unique<int>(2)));
    map.insert(std::make_pair("c", std::make_unique<int>(3)));
    
    map_type::iterator it = std::min_element(std::begin(map), std::end(map),
                                             [](map_type::const_reference p1, map_type::const_reference p2) {
                                               return *p1.second < *p2.second;
                                             });