如何从基于范围的循环中的向量中擦除? [英] how to erase from vector in range-based loop?

查看:65
本文介绍了如何从基于范围的循环中的向量中擦除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想擦除基于范围的循环中的指定元素:

  vector< int> vec = {3,4,5,6,7,8}; 
for(auto& i:vec)
{
if(i> 5)
vec.erase(& i);
}

怎么了?

解决方案

您不能按 std :: vector 上的值擦除元素,并且由于基于范围的循环直接暴露了您的值代码没有意义( vec.erase(& i))。



主要问题是 std :: vector 在擦除元素时会使其迭代器无效。



因此,基于范围的循环是基本上实现为

  auto begin = vec.begin(); 
auto end = vec.end()
for(auto it = begin; it!= end; ++ it){
..
}

然后擦除值会使 it 无效并破坏连续的迭代。 / p>

如果您确实要在迭代时删除元素,则必须注意正确更新迭代器:

  for(自动it = vec.begin(); it!= vec.end(); / *无* /)
{
if((* it)> ; 5)
it = vec.erase(it);
else
++ it;
}


I simply wanna erase the specified element in the range-based loop:

vector<int> vec = { 3, 4, 5, 6, 7, 8 };
for (auto & i:vec)
{
    if (i>5)
    vec.erase(&i);
}

what's wrong?

解决方案

You can't erase elements by value on a std::vector, and since range-based loop expose directly values your code doesn't make sense (vec.erase(&i)).

The main problem is that a std::vector invalidates its iterators when you erase an element.

So since the range-based loop is basically implemented as

auto begin = vec.begin();
auto end = vec.end()
for (auto it = begin; it != end; ++it) {
  ..
}

Then erasing a value would invalidate it and break the successive iterations.

If you really want to remove an element while iterating you must take care of updating the iterator correctly:

for (auto it = vec.begin(); it != vec.end(); /* NOTHING */)
{
  if ((*it) > 5)
    it = vec.erase(it);
  else
    ++it;
}  

这篇关于如何从基于范围的循环中的向量中擦除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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