Martin G
Martin G

Reputation: 18129

Inserting unique pointers in deep std::unordered_map

How do I insert unique pointers in this deep unordered map that I have?

std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unique_ptr<MyStruct>>>>

(C++14)

Upvotes: 2

Views: 195

Answers (2)

Martin G
Martin G

Reputation: 18129

This was the method i came up with:

std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unique_ptr<MyStruct>>>> myMap;
auto ptr = std::make_unique<MyStruct>();

// Insert at 17, 18, 19:
std::unordered_map<uint64_t, std::unique_ptr<MyStruct>> tmpLevel3Map;
tmpLevel3Map.emplace(19, std::move(ptr));
std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unique_ptr<MyStruct>>> tmpLevel2Map;
tmpLevel2Map.emplace(18, std::move(tmpLevel3Map));
myMap.emplace(17, std::move(tmpLevel2Map));

Upvotes: 0

Eugene
Eugene

Reputation: 7688

Given a map

std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unique_ptr<MyStruct>>>> m;

and aunique_ptr

auto s = std::make_unique<MyStruct>();

you can insert the it in the map like this:

m[1][2][3] = std::move(s);

Upvotes: 2

Related Questions