基于范围跳过基于'指数'?

Jay*_*Jay 11 c++ for-loop c++11

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

通常我们需要对容器的第一个元素执行一些特殊操作,并迭代其余元素.
我正在寻找像c++11_get_index_of这个伪代码中的语句:

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

  // do something with remaining elements
}
Run Code Online (Sandbox Code Playgroud)

我真的想避免回到那个场景中的旧式手动迭代器处理代码.

Ali*_*Ali 24

通常我们需要对容器的第一个元素执行一些特殊操作,并迭代其余元素.

到目前为止,我没有人提出这个解决方案,我感到很惊讶:

  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
  }
Run Code Online (Sandbox Code Playgroud)

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

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

std::size_t index = 0;

for (auto& elem : container) {

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

  // iterate over the rest of the container
}
Run Code Online (Sandbox Code Playgroud)

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

  • 绝对更喜欢循环外的分支 (3认同)

Sam*_*ett 6

Boost 提供了一种简洁的方式来做到这一点:

std::vector<int> xs{ 1, 2, 3, 4, 5 };
for (const auto &x : boost::make_iterator_range(xs.begin() + 1, xs.end())) {
  std::cout << x << " ";
}
// Prints: 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

您可以make_iterator_rangeboost/range/iterator_range.hpp标题中找到。