[英]Store multiple types as values in C++ dictionary?
我想編寫一個行為幾乎等同於 Python 字典的 C++ 對象。 C++ 的std::map
和std::unordered_map
包含 Python 字典已有的一些功能,但缺少最重要的功能之一,即能夠添加任意對象和類型。 即使不可能,您離實現 Python 字典的功能還有多遠?
之前的一些問題( 此處和此處)無法處理向字典添加多種類型的問題。
例如,我希望能夠在 C++ 中做這樣的事情:
my_dict = {'first': 1,
'second': "string",
'third': 3.5,
'fourth': my_object}
my_dict['fifth'] = list([1, 2, 3])
我能想到的最好的解決方案是使用指向被重新解釋的數據的void
指針,或者某種具有某些類型限制的運行時多態性?
我能想到的最佳解決方案是使用指向重新解釋的數據的空指針,或者某種具有某些類型限制的運行時多態性?
在我看來,現代 C++ 中的許多空指針和對指針的許多重新解釋應該是一個糟糕設計的信號。 我相信多態性將是一種方法。
此外,如果您想要使用固定數量的類型,請考慮使用 C++17 的std::any或std::variant ,這是一個更現代的union
。
#include <iostream>
#include <map>
#include <string>
#include <variant>
typedef std::map<std::variant<int, std::string>, std::variant<int, std::string>> Dict;
int main(){
Dict d;
d["key"] = 1;
d[5] = "woah";
std::cout << std::get<int>(d["key"]) << std::endl; // prints 1
// edit: print all the keys in d
for(auto& k_v: d){
std::visit(
[](auto& value){std::cout << value << ' ';},
k_v.first // k_v.second to print all values in d
);
}
}
上面的示例在某些用例中可能很有用。
還要查看 json 對象是如何在任何 C++ json 庫中實現的。 它可能會有所幫助。
編輯:我添加了一個std::visit
示例,它遍歷字典中的鍵。
我正在尋找類似的解決方案,將我的python
實驗的參數硬編碼到c++
。 我發現std'17 variant
模塊非常有用。
#include <iostream>
#include <map>
#include <variant>
#include <vector>
#include <string>
int main(){
typedef std::map<std::variant<std::string, int>, std::variant<int, double, float, std::string>> Dict;
std::vector<Dict> params = {
{
{"label", "Labs"},
{"dir", "/media/sf_Data/"},
{"num_frames", 4},
{"scale_factor", 1.0},
{5, "my number five"},
}, // Dict 0
{
{"label", "Airplanes"},
{"dir", "/media/m_result/"},
{"num_frames", 5},
{"scale_factor", 0.5},
{5, "number five"},
} // Dict 1
};
int idx = 1;
std::string label = std::get<std::string>(params[idx]["label"]);
std::string folder = std::get<std::string>(params[idx]["dir"]);
int num_frames = std::get<int>(params[idx]["num_frames"]);
double scf = std::get<double>(params[idx]["scale_factor"]);
std::string nbstr = std::get<std::string>(params[idx][5]);
std::cout << label << std::endl;
std::cout << folder << std::endl;
std::cout << num_frames << std::endl;
std::cout << scf << std::endl;
std::cout << nbstr << std::endl;
return 0;
}
結果:
Airplanes
/media/m_result/
5
0.5
number five
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.