温馨提示×

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

c++
小亿
104
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