在基于“索引”的范围内跳过? [英] Skipping in Range-based for based on 'index'?

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

问题描述

有一种方法可以访问迭代器(假设在基于C ++ 11范围的for循环中没有循环索引 ..?)。

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

通常,我们需要对容器的第一个元素做一些特殊的事情,并对其余的元素进行迭代。

我正在寻找类似于 c>< / c>< / c>语句中的 语句:

Often we need to do something special with the first element of a container and iterate over the remaining elements.
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
}

'd真的很想避免回到该场景中的旧式手动迭代器处理代码。 / p>

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

推荐答案


通常我们需要对
容器的第一个元素

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.

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

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