如何将 Python 字典翻译成 C++?

如何将 Python 字典翻译成 C++?

Python 字典是一种哈希表。你可以使用 C++ 中的 map 数据结构模拟 Python 字典的行为。你可以使用以下方式在 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;
}

这将输出以下内容:

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

请注意,这个 map 等同于 Python 中的字典:

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

更多Python相关文章,请阅读:Python 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程