溫馨提示×

c++中unordered_map遍歷的方法是什么

c++
小億
305
2023-12-21 23:40:51
欄目: 編程語言

在C++中,可以使用迭代器來遍歷std::unordered_map。以下是一種常見的方法:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<int, std::string> myMap = {
        {1, "one"},
        {2, "two"},
        {3, "three"}
    };

    // 使用迭代器遍歷unordered_map
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }

    return 0;
}

輸出結果:

Key: 3, Value: three
Key: 2, Value: two
Key: 1, Value: one

在上面的示例中,myMap.begin()返回一個指向unordered_map的第一個元素的迭代器,myMap.end()返回一個指向unordered_map的尾后元素(即最后一個元素之后的位置)的迭代器。我們使用for循環遍歷這些迭代器,并使用it->first訪問鍵,it->second訪問值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女