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

   2024-11-04 8550
核心提示:在C++中,可以使用迭代器来遍历和删除hashmap中的元素。以下是一种常见的方法:#include iostream#include unordered_mapint mai

在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递增到下一个元素,以避免遍历时跳过元素或发生未定义的行为。

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

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