【问题标题】:How to use std::min_element on map with unique pointer values? (C++)如何在具有唯一指针值的地图上使用 std::min_element? (C++)
【发布时间】:2021-06-09 13:53:42
【问题描述】:

我有一个具有唯一指针值的映射,并希望获得对具有最小值的对的引用。我正在使用下面的代码来执行此操作,但在我调用std::min_element 的行中出现错误。错误消息是:no matching function for call to object...。我应该怎么做才能解决这个问题?

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

【问题讨论】:

  • 不应该pair_typestd::pair&lt;const std::string, std::unique_ptr&lt;int&gt;&gt; 吗?考虑改用decltype(map)::value_type
  • decltype(map)::reference
  • std::make_unique 不是 C++11,如果您允许 C++14,那么您可以在 lambda 中使用 auto
  • 旁白:map.emplace("a", std::make_unique&lt;int&gt;(1)); 的转化率低于insert(make_pair(...))
  • emplace 将参数转发给 value_type 构造函数。 make_pair 将生成一个std::pair&lt;const char[2], std::unique_ptr&lt;int&gt;&gt;,然后由不同的value_type 构造函数转换

标签: c++ algorithm stl c++17 smart-pointers


【解决方案1】:

std::map的值类型是std::pair&lt;const Key, Value&gt;,当它在地图中时你不能编辑它。

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

【讨论】:

  • 非常感谢@Caleth。 map_type::referencemap_type::value_type 有什么区别?在上面的评论中,弗朗索瓦建议改用value_type
  • @Jack 您需要将map_type::value_type 与& 一起使用,就像您使用pair_type 一样
  • @Jack value_type 相当于您的pair_type 的固定版本。在这种情况下,使用 referencevalue_type &amp; 是等效的。
  • 啊,有道理。谢谢大家的cmets。
  • map_type::reference 定义为map_type::value_type &amp;,类似地const_reference 定义为const value_type &amp;
猜你喜欢
  • 2018-03-22
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
相关资源
最近更新 更多