c++

C++ HashMap支持迭代器吗

小樊
85
2024-08-02 18:24:12
栏目: 编程语言

是的,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容器。可以根据需要对键值对进行操作。

0
看了该问题的人还看了