2014-09-26 39 views
0

我在unordered_set中插入一个对象。 我想在插入/之后得到实际的对象拷贝。std :: unordered_set insert获取对象

#include <iostream> 
#include <unordered_set> 
#include <string> 

int main (void) 
{ 
    std::unordered_set<std::string> sentence; 

    auto res = sentence.insert("alex"); 
    if (res.second) 
     std::cout << *res.first << std::endl; 

    return 0; 
} 

以上简单的例子,工作正常。 当我尝试它与我的自定义类:

std::unordered_set<Policy> _policies; 
... 
... 
if (std::shared_ptr<Policy> policy = calculatePolicy (state, action, 0.f)) 
{ 
    auto res = _policies.insert (*policy); 
    if (res.second) 
     return std::make_shared<Policy>(*res.first); 

我得到:

no known conversion for argument 1 from ‘std::__detail::_Node_const_iterator<Policy, true, true>’ to ‘const Policy&’ 

为什么我会得到一个const MyClass的&的的std :: _详细:: _ Node_const_iterator isntead?

如何获取刚刚插入的对象的引用?

+1

将'_policies' var的设置声明添加到发布的问题代码中。这一点很重要。我有一种感觉,如果你没有在你的设置中存储'std :: shared_ptr ',你应该。 (它看起来不像你)。 – WhozCraig 2014-09-26 22:10:18

+0

是R Sahu,对不起,错字 – 2014-09-26 22:15:47

+0

@WhozCraig不,我不是我正在使用Policy对象。我已经将它更改为std :: unordered_set >,我没有收到编译错误。谢谢,谨慎地阐述为什么会发生这种情况? – 2014-09-26 22:17:58

回答

3

unordered_set的成员必须是const,以便它们的哈希不会更改 - 这会破坏基础数据结构。迭代器在first元素的类型中执行const

+0

因此,基本上我不能访问插入的对象,以避免打破常量? – 2014-09-26 22:24:30

+0

@Alex你可以访问,但它必须是'const'访问。您可以以任何方式检查对象,但不允许更改。 – 2014-09-26 22:25:42

+0

谢谢,这很有道理 – 2014-09-26 22:58:02

0

要修正编译器错误,改变线

return std::make_shared<Policy>(*res.first); 

return std::make_shared<Policy>(*(*res.first)); 

*res.firstshared_ptr*(*res.first)是对基础Policy对象的引用。