如何使用迭代器删除std :: map的元素? [英] How can I delete elements of a std::map with an iterator?

查看:274
本文介绍了如何使用迭代器删除std :: map的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想循环通过 std :: map 并根据其内容删除项目。

I would like to loop through an std::map and delete items based on their contents. How best would this be done?

推荐答案

这里有一种方法:

std::map<K, V>::iterator itr = myMap.begin();
while (itr != myMap.end()) {
    if (ShouldDelete(*itr)) {
       std::map<K, V>::iterator toErase = itr;
       ++itr;
       myMap.erase(toErase);
    } else {
       ++itr;
    }
}

由于C ++ 11 code> std :: map :: erase iface),它可以简化为:

Since C++11 (due to change to std::map::erase iface) it can be simplified to:

std::map<K, V>::iterator itr = myMap.begin();
while (itr != myMap.end()) {
    if (ShouldDelete(*itr)) {
       itr = myMap.erase(itr);
    } else {
       ++itr;
    }
}

这个想法是让迭代器从开始的容器到结束,在每个步骤检查当前键/值对是否应该删除。如果是这样,则迭代器的副本进行并且迭代器前进到下一步(以避免迭代器无效),然后将复制的迭代器从容器中移除。

The idea is to walk the iterator forward from the start of the container to the end, checking at each step whether the current key/value pair should be deleted. If so, a copy of the iterator is made and the iterator is advanced to the next step (to avoid iterator invalidation), then the copied iterator is removed from the container. Otherwise, the iterator is advanced as usual.

另一种常见的方法如下所示:

Another common approach is seen here:

std::map<K, V>::iterator itr = myMap.begin();
while (itr != myMap.end()) {
    if (ShouldDelete(*itr)) {
       myMap.erase(itr++);
    } else {
       ++itr;
    }
}

这使用 itr ++ 返回旧迭代器过去的值,作为向前推进步骤的副作用。

This uses the fact that itr++ returns the value that the old iterator used to have as a side-effect of advancing it forward a step.

这篇关于如何使用迭代器删除std :: map的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆