如何使用迭代器删除 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有一个兼容 C++11 的编译器,那么有一个简单的方法可以做到这一点:
这个想法是将迭代器从容器的开头向前移动到结尾,在每一步检查当前的键/值对是否应该被删除。如果是这样,我们使用 Erase 成员函数删除迭代的元素,然后该函数将迭代器返回到映射中的下一个元素。否则,我们将迭代器正常向前推进。
如果您没有符合 C++11 标准的编译器,或者您正在使用较旧的代码库,那么事情会有点棘手。在 C++11 之前,
erase
成员函数不会返回指向映射中下一个元素的迭代器。这意味着为了在迭代时删除元素,您需要使用三部分的舞蹈:erase
。此处显示:
此过程是必需的,因为如果您只是在迭代器上调用
erase
,您就会使其无效,这意味着诸如递增和递减之类的操作将导致未定义行为。上面的代码通过设置迭代器的副本来解决这个问题,前进itr
使其位于下一个元素,然后删除迭代器的临时副本。使用一些巧妙的技巧,可以以牺牲可读性为代价来缩小此代码。以下模式在较旧的 C++ 代码中很常见,但在 C++11 中不是必需的:
这里使用后自增运算符是复制旧迭代器的巧妙方法(请记住,后缀 ++ 运算符返回原始迭代器值的副本),同时还推进旧迭代器。
If you have a C++11-compliant compiler, here's an easy way to do this:
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, we remove the element iterated over using the
erase
member function, which then returns an iterator to the next element in the map. Otherwise, we advance the iterator forward normally.If you do not have a C++11-compliant compiler, or you're working with an older codebase, things are a bit trickier. Before C++11, the
erase
member function would not return an iterator to the next element in the map. This meant that in order to remove an element while iterating, you'd need to use a three-part dance:erase
on the copy of the old iterator.This is shown here:
This process was required because if you just called
erase
on the iterator, you'd invalidate it, meaning that operations like increment and decrement would lead to undefined behavior. The above code gets around this by setting up a copy of the iterator, advancingitr
so that it's at the next element, then erasing the temporary copy of the iterator.Using some Clever Trickiness, it's possible to shrink this code down at the expense of readability. The following pattern is common in older C++ code, but isn't necessary in C++11:
The use of the post-increment operator here is a clever way of making a copy of the old iterator (remember that a postfix ++ operator returns a copy of the original iterator value) while also advancing the older iterator.
编辑:似乎这仅适用于 MSVC
edit2:在 c++0x 中,这也适用于关联容器
edit: seems that this works in MSVC only
edit2: in c++0x this works for associative containers too
这是一种简单的方法:
This is one simple way: