How can I iterate through a string and also know the index (current position)?

前端 未结 7 704
小蘑菇
小蘑菇 2020-12-14 14:27

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

7条回答
  •  [愿得一人]
    2020-12-14 15:03

    A good practice would be based on readability, e.g.:

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

    Or:

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

    Or your original:

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

    Etc. Whatever is easiest and cleanest to you.

    It's not clear there is any one best practice as you'll need a counter variable somewhere. The question seems to be whether where you define it and how it is incremented works well for you.

提交回复
热议问题