如何高效地遍历C++ unordered_map

   2024-10-05 7150
核心提示:在遍历C++ unordered_map时,可以使用迭代器来实现高效遍历。以下是一种常用的方法:#include iostream#include unordered_mapin

在遍历C++ unordered_map时,可以使用迭代器来实现高效遍历。以下是一种常用的方法:

#include <iostream>#include <unordered_map>int main() {    std::unordered_map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};        for(auto it = myMap.begin(); it != myMap.end(); ++it) {        std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;    }        return 0;}

在这个例子中,我们使用迭代器it来遍历unordered_mapmyMap。通过it->first和it->second可以访问键和值。这种方法避免了使用at()或[]方法,因为这些方法会导致unordered_map的重新哈希,降低遍历效率。

除了使用迭代器,C++11引入了范围for循环,也可以用来遍历unordered_map:

for(const auto& pair : myMap) {    std::cout << "Key: " << pair.first << " Value: " << pair.second << std::endl;}

这种方法更加简洁明了,但在某些情况下可能会影响性能。因此,根据实际情况选择合适的遍历方法来高效地遍历C++ unordered_map。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号