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

前端 未结 7 706
小蘑菇
小蘑菇 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)...

提交回复
热议问题