提问者:小点点

如何在具有唯一指针值的地图上使用std::min_element?(C++)


我有一个具有唯一指针值的映射,并希望获得对具有最小值的对的引用。我使用下面的代码来实现这一点,但是在调用std::min_element的行中出现了一个错误。错误消息为:调用对象时没有匹配函数...。我该怎么做才能解决这个问题?

  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;
                                         });


共1个答案

匿名用户

std::map的值类型为std::pair,当键在映射中时,您不能编辑它。

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;
                                         });

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|唯一|指针|值|图上|std|min_element|c++)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?