Alex Caruso
Alex Caruso

Reputation: 27

Can you use advance() in a string::iterator in C++?

        for( string::iterator it = line.begin(); it != line.end(); it++ )
        {
            advance( it, 1 );
        }

I get a segmentation fault. I'm trying to get the next value in the iterator so that I can compare it to a hexadecimal.

Upvotes: 1

Views: 883

Answers (2)

Deduplicator
Deduplicator

Reputation: 45654

You sure can use advance there, but beware:

Unless you break the loop before you get too near to the end, or the length of the string is even, you will have a buffer-overrun and UB.

for( string::iterator it = line.begin(); it != line.end(); it++ )
{
    advance( it, 1 );
}

Is equivalent too:

for(auto it = line.begin(); it != line.end(); it += 2 )
{}

Because advance(it, 1); is equivalent to ++i;.
See here: http://en.cppreference.com/w/cpp/iterator/advance

If you only want the next value, check for its existence with it+1 != line.end() and get it with it[1].

Upvotes: 2

CleoR
CleoR

Reputation: 815

It looks like you may want to change it++ to ++it. I referenced this example case here http://www.cplusplus.com/reference/string/string/begin/. I think that will advance the iterator for you, so I don't think you'll need both that and advance. Try something like this,

string::iterator it = line.begin();
while(it != line.end()){
  //Do something with the iterator
  advance( it, 1 );
}

This is another reference that I found useful. http://www.cplusplus.com/reference/iterator/advance/

Upvotes: 0

Related Questions