[英]How to use std::min_element on map with unique pointer values? (C++)
我有一個具有唯一指針值的 map,並希望獲得對具有最小值的對的引用。 我正在使用下面的代碼來執行此操作,但是在調用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;
});
std::map
的值類型是std::pair<const Key, Value>
,當它在 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;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.