【发布时间】:2010-11-21 20:25:17
【问题描述】:
通常在遍历字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,而且对位置(索引)感兴趣。要通过使用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++ 中迭代可枚举对象并跟踪当前索引的最佳做法是什么?
【问题讨论】:
-
注意第二个代码块! str.length() 是 std::string::size_type 类型,所以你需要用 std::string::size_type 声明变量 i 否则编译器会给你不必要的警告。