如何在基于“索引"的基于范围的for循环中跳过元素? [英] How can I skip elements in a range-based for loop based on 'index'?

查看:81
本文介绍了如何在基于“索引"的基于范围的for循环中跳过元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基于C ++ 11范围的for循环中是否可以访问迭代器(我想没有循环索引?)?

Is there a way to access the iterator (I suppose there's no loop index?) in a C++11 range-based for loop?

通常,我们需要对容器的第一个元素做一些特殊的事情,然后遍历其余元素.因此,我正在此伪代码中查找类似于 c ++ 11_get_index_of 语句的内容:

Often we need to do something special with the first element of a container and iterate over the remaining elements. So I'm looking for something like the c++11_get_index_of statement in this pseudo-code:

for (auto& elem: container) 
{
  if (c++11_get_index_of(elem) == 0)
     continue;

  // do something with remaining elements
}

我真的很想避免回到老式的手动迭代器处理方式在这种情况下的代码.

I'd really like to avoid going back to old-style manual iterator handling code in that scenario.

推荐答案

通常我们需要对a的第一个元素做一些特殊的事情容器并遍历其余元素.

Often we need to do something special with the first element of a container and iterate over the remaining elements.

令我惊讶的是,到目前为止还没有人提出这个解决方案:

I am surprised to see that nobody has proposed this solution so far:

  auto it = std::begin(container);

  // do your special stuff here with the first element

  ++it;

  for (auto end=std::end(container); it!=end; ++it) {

      // Note that there is no branch inside the loop!

      // iterate over the rest of the container
  }

它具有将分支移出循环的巨大优势.它使循环更简单,也许编译器也可以更好地对其进行优化.

It has the big advantage that the branch is moved out of the loop. It makes the loop much simpler and perhaps the compiler can also optimize it better.

如果您坚持基于范围的for循环,也许最简单的方法是这样(还有其他更丑陋的方法):

If you insist on the range-based for loop, maybe the simplest way to do it is this (there are other, uglier ways):

std::size_t index = 0;

for (auto& elem : container) {

  // skip the first element
  if (index++ == 0) {
     continue;
  }

  // iterate over the rest of the container
}

但是,如果您只需要跳过第一个元素,我会认真地将分支移出循环.

However, I would seriously move the branch out of the loop if all you need is to skip the first element.

这篇关于如何在基于“索引"的基于范围的for循环中跳过元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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