如何解决C++ 有像 Python 字典那样的数据结构吗?
我是 C++ 的新手。我以前使用 Python 字典来存储数据,现在我正在使用 C++。 C++ 是否也有像 Python 的字典这样的数据结构?
我的场景如下,
我们在网络中有 4 个流,并为每个流分配一个路由。因此,在python中我们可以:
dictFlowRoute = {"flow1":(1,2,3,4),#flow1 is sent by node 1 to node 4.
"flow2":(1,5,"flow3":(1,3),"flow4":(2,1,5)}
基于给定的路由(dictFlowRoute),我们可以知道每对节点传输了哪些流。 例如,“flow1”和“flow3”是由节点对(1,2)传输的。在python中,我们可以生成另一个字典来存储这些数据,
dictNodePairwithFlow = { (1,2):("flow1","flow3"),(2,3): ("flow1","flow4"),(3,4): ("flow1","flow2"),(1,5): ("flow2",(5,3): ("flow2","flow3")}
因此,在C++中,如何呈现dictFlowRoute,以及如何根据给定的dictFlowRoute生成dictNodePairwithFlow?
解决方法
Python 的 Dictionary
数据类型是 associative array。在 C++ 中,我们有两个选项可供选择,std::map
和 std::unordered_map
。主要区别在于 std::map
使用 Self Balancing Red-Black Tree 和 std::unordered_map
使用 Hash Table 实现。因此,std::unordered_map
通常比 std::map
快。
对于您的情况,请使用 std::unordered_map
进行演示。与 Python 不同的是,我们不使用 Key:Value
来初始化地图,而是可以使用 []
运算符。
#include <unordered_map> // For the std::unordered_map implementation.
#include <string> // For the std::string implementation.
...
std::unordered_map<std::string,std::array<int,4>> dictFlowRoute;
dictFlowRoute["flow1"] = { 1,2,3,4 };
dictFlowRoute["flow2"] = { 1,5,4 };
dictFlowRoute["flow3"] = { 1,3 };
dictFlowRoute["flow4"] = { 2,1,5 };
std::unordered_map<std::pair<int,int>,std::pair<std::string,std::string>> dictNodePairwithFlow;
dictNodePairwithFlow[std::make_pair(1,2)] = std::make_pair("flow1","flow3");
dictNodePairwithFlow[std::make_pair(2,3)] = std::make_pair("flow1","flow4");
dictNodePairwithFlow[std::make_pair(3,4)] = std::make_pair("flow1","flow2");
dictNodePairwithFlow[std::make_pair(1,5)] = std::make_pair("flow2","flow4");
dictNodePairwithFlow[std::make_pair(5,3)] = std::make_pair("flow2","flow3");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。