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

前端 未结 7 702
小蘑菇
小蘑菇 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:01

    I would use it-str.begin() In this particular case std::distance and operator- are the same. But if container will change to something without random access, std::distance will increment first argument until it reach second, giving thus linear time and operator- will not compile. Personally I prefer the second behaviour - it's better to be notified when you algorithm from O(n) became O(n^2)...

    0 讨论(0)
  • 2020-12-14 15:02

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 15:09

    For strings, you can use string.c_str() which will return you a const char*, which can be treated as an array, example:

    const char* strdata = str.c_str();
    
    for (int i = 0; i < str.length(); ++i)
        cout << i << strdata[i];
    
    0 讨论(0)
  • 2020-12-14 15:11

    Like this:

    
        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;
    
    0 讨论(0)
  • 2020-12-14 15:13

    Since std::distance is only constant time for random-access iterators, I would probably prefer explicit iterator arithmetic. Also, since we're writing C++ code here, I do believe a more C++ idiomatic solution is preferable over a C-style approach.

    string str{"Test string"};
    auto begin = str.begin();
    
    for (auto it = str.begin(), end = str.end(); it != end; ++it)
    {
        cout << it - begin << *it;
    }
    
    0 讨论(0)
提交回复
热议问题