温馨提示×

C++ HashMap支持迭代器吗

c++
小樊
86
2024-08-02 18:24:12
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

是的,C++的std::unordered_map和std::map容器都支持迭代器。通过迭代器可以遍历HashMap中的每个键值对,并进行相应的操作。具体可以使用begin()和end()方法来获取起始和结束迭代器,使用++操作符来递增迭代器。示例代码如下:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<int, std::string> hashMap;
    
    hashMap[1] = "apple";
    hashMap[2] = "banana";
    hashMap[3] = "cherry";
    
    for(auto it = hashMap.begin(); it != hashMap.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }
    
    return 0;
}

上述代码展示了如何使用迭代器遍历一个unordered_map容器。可以根据需要对键值对进行操作。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++中hashmap遍历删除的方法是什么

0