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