如何遍历字符串并知道索引(当前位置)?

pie*_*fou 54 c++ string iterator

通常在迭代字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,还对位置(索引)感兴趣.要通过使用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++中迭代可枚举对象并跟踪当前索引的最佳实践是什么?

Lea*_*elo 49

像这样:


    std::string s("Test string");
    std::string::iterator it = s.begin();

    //Use the iterator...
    ++it;
    //...

    std::cout << "index is: " << std::distance(s.begin(), it) << std::endl;
Run Code Online (Sandbox Code Playgroud)


The*_*ish 46

我从来没有听说过这个具体问题的最佳实践.但是,一般的最佳实践是使用解决问题的最简单的解决方案.在这种情况下,数组样式访问(或c样式,如果你想称之为)是最简单的迭代方式,同时索引值可用.所以我肯定会这样推荐.

  • 一个例子会很好:P (5认同)

And*_*rew 21

您可以使用前面提到的标准STL功能距离

index = std::distance(s.begin(), it);
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用类似c的界面访问字符串和其他一些容器:

for (i=0;i<string1.length();i++) string1[i];
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,在我的实现索引中,迭代器的工作速度要快得多(5倍以上) (2认同)

Ale*_*lds 10

一个好的做法是基于可读性,例如:

string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it)
   cout << index++ << *it;
Run Code Online (Sandbox Code Playgroud)

要么:

string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it, ++index)
   cout << index << *it;
Run Code Online (Sandbox Code Playgroud)

或者你原来的:

string str ("Test string");
int index = 0;
for (auto it = str.begin() ; it < str.end(); ++it, ++index)
   cout << index << *it;
Run Code Online (Sandbox Code Playgroud)

等等.对你来说最简单,最干净的事情.

目前尚不清楚是否有任何一种最佳实践,因为你需要一个计数器变量.问题似乎在于您定义它的位置以及增量如何适合您.

  • 我之前的编辑是正确的,@Alex Reynolds。检查[在`C++`中的`for`循环的初始化体中不能声明两个不同类型的变量。]​​(/sf/ask/188117471/ -two-variables-of-different-types-in-a-for-loop) 和 [this](https://ideone.com/lngBfo)。 (2认同)