unique_ptr unordered_map:无法从迭代器获取价值

unordered_map of unique_ptr: can't get value from iterator

本文关键字:迭代器 获取 ptr unordered map unique      更新时间:2023-10-16

我正在尝试将unique_ptr存储在一个无序映射中。我使用以下代码:

#include <unordered_map>
#include <memory>
int *function()
{
    std::unordered_map< int, std::unique_ptr<int> > hash;
    auto iterator=hash.find(5);
    return iterator->second().get();
}

当我试图编译这个(gcc 4.7.2)时,我得到了以下错误:

test.cpp: In function ‘int* function()’:
test.cpp:9:29: error: no match for call to ‘(std::unique_ptr<int>) ()’

我不明白这个代码出了什么问题。就好像我需要使用另一种方法从迭代器中提取引用,但我不知道怎么做

Shachar

此行:

return iterator->second().get();

应该是这样的:

return iterator->second.get();

CCD_ 1不是函数,而是映射中包含的CCD_。您现在拥有的代码尝试调用成员变量上的()运算符。但是由于std::unique_ptr(存储在second中)没有定义这样的运算符,编译器无法找到它

secondstd::pair的成员变量,但您试图像函数一样调用它。请使用以下内容。

return iterator->second.get();