![](/img/trans.png)
[英]std::unordered_set insert, get the position where item was inserted
[英]std::unordered_set insert get the object
我在unordered_set中插入对象。 我想从集合中/如果插入后获得实际的对象副本。
#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 :: _ detail :: _ Node_const_iterator注释?
如何获得对刚刚插入的对象的引用?
unordered_set
的成员必须为const
以便其哈希值不变-这会破坏基础数据结构。 迭代器在first
元素的类型中强制使用const
。
要修复编译器错误,请更改行
return std::make_shared<Policy>( *res.first );
至
return std::make_shared<Policy>( *(*res.first) );
*res.first
是shared_ptr
。 *(*res.first)
是对基础Policy
对象的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.