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


Python 字典是一个哈希映射。你可以使用 C++ 中的 map 数据结构来模拟 Python dict 的行为,即你可以如下在 C++ 中使用 map

#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

请注意,此 map 等同于 python dict

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

更新于:17-06-2020

1K+ 次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.