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

前端 未结 7 719
小蘑菇
小蘑菇 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: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;
    }
    

提交回复
热议问题