【问题标题】:Does C++ have a data structure like a Python dictionary?C++ 有像 Python 字典这样的数据结构吗?
【发布时间】:2023-03-30 20:07:01
【问题描述】:

我是 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),我们可以知道每对节点传输了哪些流。 例如“flow1”和“flow3”是通过节点对(1,2)传输的。在python中,我们可以生成另一个字典来存储这些数据,

dictNodePairwithFlow = { (1,2):("flow1","flow3"),
                         (2,3): ("flow1","flow4"),
                         (3,4): ("flow1","flow2"),
                         (1,5): ("flow2", "flow4"),
                         (5,3): ("flow2","flow3")}

因此,在C++中,如何呈现dictFlowRoute,如何根据给定的dictFlowRoute生成dictNodePairwithFlow

【问题讨论】:

  • “C++ 是否也有类似 Python 字典的数据结构?”是的:std::map
  • 就算没有,自己实现也没那么难。
  • 作为参考,“字典”数据结构的语言无关名称是哈希映射。
  • @jfaccioni “字典”的通用名称是“关联数组”。 Hash Map 就是其中的一种实现方式。
  • 另见std::unordered_map,它与std::map 的主要区别在于它的实现——它是一个哈希映射,而std::map 通常是一个树。现在您是一名 C++ 程序员,您可以考虑很多要优化的内容。

标签: python c++ data-structures stl


【解决方案1】:

Python 的 Dictionary 数据类型是 associative array。在 C++ 中,我们有两个选项可供选择,std::mapstd::unordered_map。主要区别在于std::map 使用Self Balancing Red-Black Treestd::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");

附加:std::pairstd::string

【讨论】:

  • std::map 不使用散列。它只使用比较。
  • @gerum 对不起,我错过了。感谢您指出!
猜你喜欢
  • 2013-04-15
  • 2021-01-15
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 2011-05-05
  • 2010-10-29
相关资源
最近更新 更多