2

在现代 C++ 中,当您只需要每个元素的值时,用于迭代像字符串或向量这样的顺序集合的习惯用法简短而优雅:

for (auto x: xs)

当您还需要索引时,它就不那么优雅了:

for (size_t i = 0; i != xs.size() ++i)

...除非有一些我还没有赶上的最近的发展。C++11 是否有首选的方式来做后者,或者上面的方式仍然像它一样好?

4

3 回答 3

2

Range-Based for loops将在现代代码中非常流行,Range-Based for Loops 适用于任何支持范围概念的类型。给定类型为 T 的对象 obj,begin(obj)并且end(obj)是有效的。包括:

  • 所有 C++11 库容器。
  • 数组和 valarrays。
  • 初始化器列表。
  • 正则表达式匹配。
  • 任何 UDT(用户定义类型) T 其中 begin(T) 和 end(T) 产生合适的迭代器。
于 2013-01-19T06:03:33.387 回答
1

首选和惯用的方式是简单的 for 循环。

替代方法包括使用整数范围:

template<typename C>
auto container_index(C const& container) -> decltype(boost::irange(0, container.size())) {
  return boost::irange(0, container.size());
}

for(auto x : container_index(xs))

或迭代函数:

template<typename F>
void index_iterate(std::size_t size, F func) {
  for(std::size_t i = 0; i != size; ++i) {
    func(i);
  }
}

index_iterate(container.size(), [&](std::size_t i){ /* ... */ });

尽可能使用简单的循环。在我看来它是优越的。

于 2013-01-19T05:52:35.847 回答
0

您可以结合两种方法:

int i = 0;
for ( auto x : v ) {
    // do smth with x or v[i] or i
    i++;
}
于 2013-01-19T06:28:10.923 回答