std::unordered_set插入获取对象
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&’
为什么我得到一个标准::_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.first
是shared_ptr
. *(*res.first)
是对基础Policy
对象的引用。
相关文章:
- 如何在C++中获取该对象的类声明中对象的地址?
- 如何在新的派生对象中获取基本对象的数据?
- 数组中不同类型的对象并获取每个对象的类型
- Visual Studio 2017 C++,不能使用 typeid() 获取信息对象,缺少指针?;
- 从两个 4x64 位整数数组中获取取模
- 如何从参数包获取指向对象的指针
- 在DelphiInterface上实现Dynamic_cast以获取基础对象类的任何方法
- 在<Object>基于范围的 for 循环中从 std::vector 获取指向对象的指针
- boost::可选 - 对对象使用 boost::in_place,构造器通过引用获取其他对象
- 如何使用 API 获取 QML 对象的 id 属性C++
- 如何从指针到方法获取类(对象类型)
- 在 C/C++ 中获取 Java 对象的内存地址
- 在ClrProfiler中,如何从ObjectID中获取托管对象
- 从操作员内部获取有关对象的RTTI信息
- 使用C 获取Java对象来调用Java方法
- 我们可以从设备句柄中获取设备对象详细信息 /名称吗?
- 从qgraphicsitem qt C 获取实际对象
- 如何获取成员对象以通知其容器对象
- 如何从静态对象中获取该对象的值
- 如何获取 COM 对象的成员函数的地址?