[英]Initialization of recurring unordered map via curly braces
我需要初始化一個實現樹狀結構的類型。
Tree t1 = 1;
Tree t2 = {{"a",t1},{"b",{{"x",2},{"y",4}}},{"c",5}};
所以我定義了繼承自 std::unordered_map 的結構。 我不得不將重復出現的“樹”包裝在智能指針中。
//tree.h
using std;
struct Tree : unordered_map<string, unique_ptr<Tree>>{
int simple;
Tree() = default;
Tree(unsigned s): simple{s}{};
Tree(const initializer_list<pair<string, unique_ptr<Tree>>> & il): simple{s} {
// does not compile, would not work anyway 'coz the pointer
};
}
我不知道如何指定初始化列表。
有一些可能會有所幫助:
struct TreeV : vector<pair<string, TreeV>>{
...
TreeV(const vector<pair<string, TreeV>> & v) : vector<pair<string, TreeV>>(v){};
}
vector<pair<string, TreeV>> t3 = {{"a",t1},{"b",{{"x",2},{"y",4}}},{"c",5}};
如何在“initializer_list”中捕獲重復的花括號結構? 或如何從花括號結構初始化 std::unordered_map 的重復模式?
從初始化列表中刪除引用。 使用非 const 引用時不能傳遞右值。 如果s
甚至沒有在任何地方定義,也從成員初始值設定項列表中刪除simple{s}
。
Tree(std::initializer_list<std::pair<std::string, std::unique_ptr<Tree>>> il) {};
然后像這樣的東西會編譯。
Tree t = {
{ "one", std::make_unique<Tree>() },
{ "two", std::unique_ptr<Tree>(new Tree({ // unique_ptr is used here because make_unique does not support initializer lists.
{
"three", std::make_unique<Tree>()
}}))
}
};
但是我會完全質疑unique_ptr
的使用,在這里使用它們有什么特別的原因嗎? 我假設 memory 無論如何都會由 unordered_map 管理? 以下是不使用unique_ptr
的情況:
// This would allow to use syntax that resembles your goal
Tree(std::initializer_list<std::pair<std::string, Tree>> il) {};
...
Tree t = {
{ "one", {} },
{ "two", {
{ "three", {} }
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.