从 unordered_map::emplace return 值访问插入的元素

Access inserted element from unordered_map::emplace return value

我正在调用 unordered_map::emplace() 并且正在存储返回值(一对)。我只想从该对中访问插入的值,但在我的一生中,我无法弄清楚这个令人困惑的对的正确配置。

我的无序地图定义:

std::unordered_map<GUID, shared_ptr<Component>> components;

我看过 unordered_map::emplace() documentation;根据这个,对中的第一个元素应该是 shared_ptr<Component> 但编译器只是不高兴。

在下面的代码中我得到了错误:Error 2 error C2227: left of '->gUid' must point to class/struct/union/generic type

class Component {
public:
    template<typename T, typename... Params>
    GUID addComponent(Params... params)
    {
        auto cmp = Component::create<T>(params...);
        auto res = components.emplace(cmp->gUid, cmp);

        if (!res.second) {
            GUID gUid;
            getNullGUID(&gUid);
            return gUid;
        }

        return (*res.first)->gUid; // compiler error here
        // *Yes I know I can do: return cmp->gUid;
    }

    GUID gUid; // initialised in constructor
    std::unordered_map<GUID, std::shared_ptr<Component>> components;
};

知道如何正确访问对的第二个值吗?

emplace 返回的对的 first 是一个 迭代器 -- 对于 unordered_map,它的作用类似于指向一个pair<key, value>。因此,要从 that 对中获取值,您需要 second:

return res.first->second->gUid;