std::string::iterator to offset and back

dongle26 picture dongle26 · Sep 19, 2012 · Viewed 12.2k times · Source
  • Can I set an iterator to position 5 in a string via some member or do I have to do a for(i = 0; i < 5; ++i) iterator++;?
  • Given an Iterator, how can I convert that to a numeric offset in the string?
  • If this is not possible with std::iterators can boost do it?

Iterators <-> Offsets

Answer

ForEveR picture ForEveR · Sep 19, 2012

Can I set an iterator to position 5 in a string via some member

You can use std::advance

std::advance(iterator, 5);

or

iterator += 5;

Given an Iterator, how can I convert that to a numeric offset in the string?

You can use std::distance

std::distance(string.begin(), iterator);

or

iterator - string.begin()