views:

208

answers:

2

In a loop running over the entire string how 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.

+3  A: 
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
        }
    }
}
Shmoopty
j_random_hacker
Ha! You're totally right. Thank you. Edited.
Shmoopty
All good! I like your 2nd snippet, much cleaner BTW. +1.
j_random_hacker
Actually, I now see that both ways will technically cause UB for an empty string. (Technically it's UB if you advance past one-past-the-end of a sequence/array, or back before the beginning -- even if you don't deref the iterator/pointer.) Sorry to nitpick...
j_random_hacker
Adjusted.......
Shmoopty
+2  A: 

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
    }
}
ephemient
+1. And unlike Shmoopty's loops (which I suggested and thus share blame for) this correctly handles the empty-container boundary case.
j_random_hacker