我如何查看字符串迭代器的下一个值

Cod*_*ain 4 c++ string iterator

在一个遍历整个循环的循环中string我如何查看迭代器的下一个值?

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

这在C中非常简单,

for (i = 0; i < strlen(str); ++i) {
     if (str[i] == str[i+1]) {
         // Processing
     }
}
Run Code Online (Sandbox Code Playgroud)

在c ++中有什么有效的方法吗?

注意:我没有使用Boost.

Dre*_*ann 5

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

要么

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

  • 通过使用`if(it + 1!= inp.end()&&*it ==*(it + 1))`来避免引用超过结尾(导致未定义的行为).-1引起你的注意,将在修复后撤销. (3认同)