Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string::iterator to offset and back

  • 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

like image 610
dongle26 Avatar asked Sep 19 '12 06:09

dongle26


2 Answers

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()
like image 133
ForEveR Avatar answered Oct 16 '22 00:10

ForEveR


std::string iterators are random access iterators, which define the +operator. You can get a iterator to position 5 with begin(str) + 5. Offset can be computed via std::distance which uses -operator for random access iterators.

like image 26
hansmaad Avatar answered Oct 16 '22 01:10

hansmaad