问题描述
通常在遍历字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,而且对位置(索引)感兴趣.要通过使用 string::iterator
来实现这一点,我们必须维护一个单独的索引:
Often when iterating through a string (or any enumerable object), we are not only interested in the current value, but also the position (index). To accomplish this by using string::iterator
we have to maintain a separate index:
string str ("Test string");
string::iterator it;
int index = 0;
for ( it = str.begin() ; it < str.end(); it++ ,index++)
{
cout << index << *it;
}
上面显示的样式似乎并不优于'c-style':
The style shown above does not seem superior to the 'c-style':
string str ("Test string");
for ( int i = 0 ; i < str.length(); i++)
{
cout << i << str[i] ;
}
在 Ruby 中,我们可以优雅地获取内容和索引:
In Ruby, we can get both content and index in a elegant way:
"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }
那么,在 C++ 中迭代可枚举对象并跟踪当前索引的最佳做法是什么?
So, what is the best practice in C++ to iterate through an enumerable object and also keep track of the current index?
推荐答案
我从未听说过针对这个特定问题的最佳实践.但是,一般来说,一种最佳实践是使用解决问题的最简单的解决方案.在这种情况下,数组样式访问(或 c 样式,如果您想这样称呼它)是在索引值可用的同时进行迭代的最简单方法.所以我当然会推荐这种方式.
I've never heard of a best practice for this specific question. However, one best practice in general is to use the simplest solution that solves the problem. In this case the array-style access (or c-style if you want to call it that) is the simplest way to iterate while having the index value available. So I would certainly recommend that way.
这篇关于如何遍历字符串并知道索引(当前位置)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!