【发布时间】: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_type是std::pair<const std::string, std::unique_ptr<int>>吗?考虑改用decltype(map)::value_type。 -
或
decltype(map)::reference -
std::make_unique不是 C++11,如果您允许 C++14,那么您可以在 lambda 中使用auto -
旁白:
map.emplace("a", std::make_unique<int>(1));的转化率低于insert(make_pair(...)) -
emplace将参数转发给value_type构造函数。make_pair将生成一个std::pair<const char[2], std::unique_ptr<int>>,然后由不同的value_type构造函数转换
标签: c++ algorithm stl c++17 smart-pointers