如何将 Python 字典翻译成 C++?
pythonprogramming更新于 2024/4/11 12:04:00
Python 字典是一个 Hashmap。您可以使用 C++ 中的 map 数据结构来模仿 Python 字典的行为。您可以在 C++ 中使用 map,如下所示:
#include <iostream> #include <map> using namespace std; int main(void) { /* Initializer_list 构造函数 */ map<char, int> m1 = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5} }; cout << "该映射包含以下元素<< endl; for (auto it = m1.begin(); it != m1.end(); ++it) cout << it->first << " = " << it->second << endl; return 0; }
将给出输出
该映射包含以下元素 a = 1 b = 2 c = 3 d = 4 e = 5
请注意,此映射等同于 Python 字典:
m1 = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }