Pietro M
Pietro M

Reputation: 1939

Iterator to a specific character in a std::string

I need an iterator to a specific character in a std::string, without looping from the beginning.

Is this the best way to do it?

std::string s("abcdefg...");
size_t id = 5;
std::string::const_iterator it = s.begin();
std::advance(it, id - 1);

Upvotes: 2

Views: 1529

Answers (2)

Xeo
Xeo

Reputation: 131867

Since std::string's iterators are random access, you can directly do this:

std::string::const_iterator it = s.begin() + (id-1);

(This is what std::advance eventually expands to for random access iterators.)

Upvotes: 4

Matteo Italia
Matteo Italia

Reputation: 126927

You can also simply do:

std::string::const_iterator it = s.begin() + (id-1);

although it should have more or less the same performance of std::advance, since, if it is a random access iterator, advance uses operator+ (otherwise it resorts to looping; this happens e.g. for list iterators).

Upvotes: 4

Related Questions