如何从 set中删除所有偶数在 c++
我是 C++ 新手。我想知道经验丰富的程序员是如何做到这一点的。
我所拥有的:
set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(4);
s.insert(5);
for(set<int>::iterator itr = s.begin(); itr != s.end(); ++itr){
if (!(*itr % 2))
s.erase(itr);
}
当然,它不起作用。因为itr在被擦除后会递增。 这是否意味着每次我从集合中删除元素后,Itr 都必须指向集合的开头?
I'm new to C++. I'd like to know how experienced coders do this.
what I have:
set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(4);
s.insert(5);
for(set<int>::iterator itr = s.begin(); itr != s.end(); ++itr){
if (!(*itr % 2))
s.erase(itr);
}
and of course, it doesn't work. because itr is incremented after it is erased.
does it mean Itr has to point to the begin of the set everytime after i erase the element from the set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Scott Myers 的有效 STL
effective STL by Scott Myers
从 std::set 中删除元素只会使指向该元素的迭代器无效。
在擦除目标元素之前获取下一个元素的迭代器。
Erasing an element from std::set only invalidates iterators pointing to that element.
Get an iterator to the next element before erasing the target element.
你不需要回到起点。
set::erase
仅使引用被擦除项的迭代器无效,因此您只需在擦除之前复制迭代器并递增:You don't need to go back to the start.
set::erase
only invalidates iterators that refer to the item being erased, so you just need to copy the iterator and increment before erasing:最好的方法是使用remove_if和erase的组合,
这会很有帮助
http://en.wikibooks.org/wiki/More_C%2B% 2B_Idioms/Erase-Remove
另请参阅 scott meyers 的有效 STL
编辑
:虽然我的解决方案是错误的,但我不会删除它。对于像我这样不了解可变/不可变迭代器的人来说,这可能是一个很好的学习The best way is to use the combination of remove_if and erase
This will be helpful
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Erase-Remove
Also Refer to effective STL by scott meyers
Edit
: Although my solution is wrong i am not deleting it. It might be a good learning for someone like me who does not about mutable/immutable iterators