【问题标题】:How do i peek at at the next value of string iterator我如何查看字符串迭代器的下一个值
【发布时间】:2010-01-08 02:40:48
【问题描述】:

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

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

这在C语言中很简单,

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

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

注意:我没有使用 Boost。

【问题讨论】:

标签: c++ string iterator


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

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

【讨论】:

  • 通过使用if (it + 1 != inp.end() &amp;&amp; *it == *(it + 1)) 来避免超出结尾(这会导致未定义行为)。 -1 引起您的注意,修复后将撤销。
  • 实际上,我现在看到两种方式在技术上都会导致 UB 为空字符串。 (从技术上讲,如果您前进超过序列/数组的末尾,或者在开始之前返回 - 即使您没有取消引用迭代器/指针,它也是 UB。)抱歉吹毛求疵...
【解决方案2】:

string 恰好提供了一个随机访问迭代器,所以 operator+(int) 存在。您可以使用 Shmoopty 的答案,既好又简单。

如果您使用仅提供双向迭代器的list&lt;&gt;,您将保留第二个迭代器。

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

【讨论】:

  • +1。与 Shmoopty 的循环(我建议并因此分担责任)不同,它正确处理了空容器边界情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 2023-03-22
  • 2012-10-23
相关资源
最近更新 更多