python字典是Hashmap。您可以在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
请注意,此映射等效于python dict:
m1 = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }