如何将 Python 字典转换成 C++?


Python 字典是哈希映射。可以在 C++ 中使用映射数据结构模拟 python 字典的行为。可以在 C++ 中使用映射,如下所示

#include <iostream>
#include <map>
using namespace std;
int main(void) {
   /* Initializer_list constructor */
   map<char, int> m1 = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Map contains following elements" << endl;
   for (auto it = m1.begin(); it != m1.end(); ++it)
   cout << it->first << " = " << it->second << endl;
   return 0;
}

这会产生以下输出

The map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

请注意,此映射等同于 python 字典

m1 = {
   'a': 1,
   'b': 2,
   'c': 3,
   'd': 4,
   'e': 5
}

更新时间: 2020-06-17

1,000+ 浏览量

开启你的 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.