2013-07-06 52 views
1

我想获取存储在unordered_map中的unique_ptr。我使用下面的代码:unique_ptr的unordered_map:无法从迭代器中获取值

#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

回答

1

secondstd::pair的成员变量,但您试图将其称为函数。改为使用以下内容。

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

D'oh!谢谢。 Mia culpa。 –

2

这条线:

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

应该是这样的:

return iterator->second.get(); 

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