本文介绍了如何迭代一个字符串,并知道索引(当前位置)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过字符串(或任何可枚举的对象)迭代时,我们不仅对当前值感兴趣,还对位置(索引)感兴趣。要通过使用 string :: iterator 来实现这一点,我们必须维护一个单独的索引:

  string str(Test string); 
string :: iterator it;
int index = 0;
for(it = str.begin(); it< str.end(); it ++,index ++)
{
cout<索引<< *它;上面的风格看起来似乎并不优于'c-style'。 p>

  string str(Test string); 
for(int i = 0; i {
cout< i<< str [i];
}



在Ruby中,我们可以以优雅的方式获得内容和索引: / p>

 hello.split()。each_with_index {| c,i | puts#{i},#{c}} 

C ++通过枚举对象进行迭代,并跟踪当前索引?

解决方案

我从来没有听说过最佳实践对于这个具体问题。然而,一般的最佳实践是使用解决问题的最简单的解决方案。在这种情况下,数组风格访问(或c风格,如果你想调用它)是最简单的方法来迭代,同时索引值可用。所以我一定会这样推荐。


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;
  }

Above style seems does not seem superior to the 'c-style'

  string str ("Test string");
  for ( int i = 0 ; i < str.length(); i++)
  {
         cout << i << str[i] ;
  }

In Ruby, we can get both content and index in a elegant way:

  "hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }

So, what is the best practice in C++ to iterate through an enumerable object and also keep track of the current index?

解决方案

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.

这篇关于如何迭代一个字符串,并知道索引(当前位置)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:11