如何將 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+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告