Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Dịch Python Dictionary sang C++

Python dict = Hashmap. C++ dùng std::map hoặc std::unordered_map.

Ví dụ C++ map

#include 
#include 
using namespace std;
int main() {
    map m1 = {{'a',1}, {'b',2}, {'c',3}, {'d',4}, {'e',5}};
    for (auto it = m1.begin(); it != m1.end(); ++it)
        cout << it->first << " = " << it->second << endl;
    return 0;
}

Kết quả: in các cặp key=value. Tương đương Python {'a':1, 'b':2, ...}.

Lưu ý: C++ map là ordered (RB-tree), unordered_map mới là hash table như Python dict.