Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 267
Tim Avatar asked Jul 19 '26 17:07

Tim


1 Answers

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
like image 145
Konrad Rudolph Avatar answered Jul 22 '26 06:07

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!