学堂 学堂 学堂公众号手机端

在C++中,可以使用迭代器来遍历和删除hashmap中的元素

lewis 1年前 (2024-04-06) 阅读数 6 #技术

在C++中,可以使用迭代器来遍历和删除hashmap中的元素。以下是一种常见的方法:

#include<iostream> #include<unordered_map> intmain(){ std::unordered_map<int,std::string>hashMap={{1,"apple"},{2,"banana"},{3,"cherry"}}; for(autoit=hashMap.begin();it!=hashMap.end();){ if(it->first==2){ it=hashMap.erase(it); }else{ ++it; } } for(auto&pair:hashMap){ std::cout<<pair.first<<":"<<pair.second<<std::endl; } return0; }

在上面的示例中,我们使用迭代器it遍历hashmap,并在满足条件时使用erase方法删除元素。请注意,在删除元素之后,需要将迭代器it递增到下一个元素,以避免遍历时跳过元素或发生未定义的行为。


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门