C++是否有一个数据结构,比如Python字典?

2024-10-03 06:19:48 发布

您现在位置: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,3,4),
                   "flow3":(1,2,5,3),
                   "flow4":(2,3,1,5)}

基于给定的路由(dictFlowRoute),我们可以知道每对节点传输哪些流例如,“流1”和“流3”通过节点对(1,2)传输在python中,我们可以生成另一个字典来存储这些数据

dictNodePairwithFlow = { (1,2):("flow1","flow3"),
                         (2,3): ("flow1","flow4"),
                         (3,4): ("flow1","flow2"),
                         (1,5): ("flow2", "flow4"),
                         (5,3): ("flow2","flow3")}
P>因此,在C++中,如何给出 DealFraseRead EEE>,以及如何根据给定的 DealFraseRouth[EEM><


Tags: 数据网络node路由数据结构字典节点新手
1条回答
网友
1楼 · 发布于 2024-10-03 06:19:48

Python的Dictionary数据类型是associative array。在C++中,我们有两个选项可以选择,^{}^{}。主要区别在于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, 3, 4 };
dictFlowRoute["flow3"] = { 1, 2, 5, 3 };
dictFlowRoute["flow4"] = { 2, 3, 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");

附加:^{}^{}

相关问题 更多 >