Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลง Python Dictionary เป็น C++

Python dictionary คือ Hashmap คุณสามารถใช้โครงสร้างข้อมูล map ใน C++ เพื่อเลียนแบบพฤติกรรมของ Python dict คุณสามารถใช้ map ใน C++ ได้ดังนี้:

#include 
#include 
using namespace std;
int main(void) {
    /* Initializer_list constructor */
    map 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
}