Ælex
Ælex

Reputation: 14839

std::unordered_set insert get the object

I am inserting an object in an unordered_set. I want to get the actual object copy from within the set after/if it is inserted.

#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;
}

The above simple example, works fine. When I try it with my custom class:

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 );

I get:

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

Why am I getting an std::_detail::_Node_const_iterator isntead of a const MyClass&?

How do I get the reference to the object that was just inserted?

Upvotes: 0

Views: 173

Answers (2)

R Sahu
R Sahu

Reputation: 206627

To fix the compiler errors, change the line

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

to

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

*res.first is the shared_ptr. *(*res.first) is a reference to the underlying Policy object.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308206

The members of an unordered_set are required to be const so that their hash doesn't change - this would break the underlying data structures. The iterator enforces const in the type of the first element.

Upvotes: 3

Related Questions