在C++中,可以使用迭代器来遍历和删除hashmap中的元素
在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
递增到下一个元素,以避免遍历时跳过元素或发生未定义的行为。
版权声明
本文仅代表作者观点,不代表博信信息网立场。