在现代 C++ 中,当您只需要每个元素的值时,用于迭代像字符串或向量这样的顺序集合的习惯用法简短而优雅:
for (auto x: xs)
当您还需要索引时,它就不那么优雅了:
for (size_t i = 0; i != xs.size() ++i)
...除非有一些我还没有赶上的最近的发展。C++11 是否有首选的方式来做后者,或者上面的方式仍然像它一样好?
Range-Based for loops
将在现代代码中非常流行,Range-Based for Loops
适用于任何支持范围概念的类型。给定类型为 T 的对象 obj,begin(obj)
并且end(obj)
是有效的。包括:
首选和惯用的方式是简单的 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){ /* ... */ });
尽可能使用简单的循环。在我看来它是优越的。
您可以结合两种方法:
int i = 0;
for ( auto x : v ) {
// do smth with x or v[i] or i
i++;
}