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

   2025-02-13 4300
核心提示:在C++中,可以使用迭代器来遍历std::unordered_map。以下是一种常见的方法:#include iostream#include unordered_mapint main()

在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: threeKey: 2, Value: twoKey: 1, Value: one

在上面的示例中,myMap.begin()返回一个指向unordered_map的第一个元素的迭代器,myMap.end()返回一个指向unordered_map的尾后元素(即最后一个元素之后的位置)的迭代器。我们使用for循环遍历这些迭代器,并使用it->first访问键,it->second访问值。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言