开发者

How do i peek at at the next value of string iterator

In a loop running over the entire string h开发者_高级运维ow do i peek at the next value of iterator?

for (string::iterator it = inp.begin(); it!= inp.end(); ++it)
{
  // Just peek at the next value of it, without actually incrementing the iterator
}

This is quite simple in C,

for (i = 0; i < strlen(str); ++i) {
     if (str[i] == str[i+1]) {
         // Processing
     }
}

Any efficient way to do above in c++?

Note: Im not using Boost.


if ( not imp.empty() )
{
    for (string::iterator it = inp.begin(); it!= inp.end(); ++it)
         if (it + 1 != inp.end() and *it == *(it + 1)) {
             // Processing
         }
    }
}

or

if ( not imp.empty() )
{
    for (string::iterator it = inp.begin(); it!= inp.end() - 1; ++it)
        if ( *it == *(it+1) ) {
            // Processing
        }
    }
}


string happens to provide a random-access iterator, so operator+(int) exists. You can use Shmoopty's answer, nice and easy.

If you were using list<>, which only provides a bidirectional iterator, you'd keep a second iterator around.

for (list<char>::iterator it(inp.begin()), next(it);
        it != inp.end() && ++next != inp.end(); it = next) {
    if (*it == *next) {
        // Processing
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜