通常当我们迭代一个字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,还对位置(索引)感兴趣。为了通过使用 string::iterator
实现这一点,我们必须维护一个单独的索引:
string str ("Test string");
string::iterator it;
int index = 0;
for ( it = str.begin() ; it < str.end(); it++ ,index++)
{
cout << index << *it;
}
上面展示的样式似乎并不比“c-style”更好:
string str ("Test string");
for ( int i = 0 ; i < str.length(); i++)
{
cout << i << str[i] ;
}
在 Ruby 中,我们可以以一种优雅的方式获取内容和索引:
"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }
那么,在C++中遍历可枚举对象并同时跟踪当前索引的最佳实践是什么?