std::unordered_set插入获取对象

std::unordered_set insert get the object

本文关键字:获取 取对象 插入 unordered std set      更新时间:2023-10-16

我在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&’

为什么我得到一个标准::_detail::_Node_const_iterator不是常量MyClass&?

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

unordered_set的成员需要const,以便它们的哈希不会改变 - 这会破坏底层数据结构。迭代器强制const first元素的类型。

要修复编译器错误,请更改行

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

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

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