how to erase from vector in range-based loop?

前端 未结 3 1878
我在风中等你
我在风中等你 2021-02-05 22:30

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

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


        
3条回答
  •  甜味超标
    2021-02-05 22:36

    It's quite simple: don't use a range-based loop. These loops are intended as a concise form for sequentially iterating over all the values in a container. If you want something more complicated (such as erasing or generally access to iterators), do it the explicit way:

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

提交回复
热议问题