c++中hashmap遍历删除的方法是什么

avatar
作者
筋斗云
阅读量:4

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

#include <iostream> #include <unordered_map>  int main() {     std::unordered_map<int, std::string> hashMap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};      for(auto it = 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;     }      return 0; } 

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!