C++ Seek a std::string::iterator to given position

Tim picture Tim · Dec 20, 2012 · Viewed 7.8k times · Source

Is it possible to seek a std::string::iterator safely to a given position?

std::string::iterator has a offset access operator (operator []), but it exists in the category defined by some people as undefined behavior, like it + 3.

cplusplus.com reference

Answer

Konrad Rudolph picture Konrad Rudolph · Dec 20, 2012

std::string::iterator has a offset access operator (operator []), but it exists in the category defined by some people as undefined behavior, like it + 3.

I don’t understand this statement. There is no such category. std::basic_string<>::iterator is a random access iterator and as such you can seek by just adding or subtracting an offset to / from it (which is consistent with the documentation you linked to):

auto new_it = it + offset;

What’s undefined is seeking past the end() iterator of the associated container, or before its beginning. That is, the following is undefined behaviour:

std::string str = "hi";
auto it1 = str.begin() + 2; // OK.
assert(it1 == str.end());
auto it2 = str.begin() + 3; // UB!
// At this point we cannot assert anything about it2