Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-06-24) 阅读数 7 #程序编程
文章标签 c++

在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访问值。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门