【问题标题】:The loop exits only after one of the iterator has reached the end. What is wrong here?循环仅在迭代器之一到达末尾后退出。这里有什么问题?
【发布时间】:2021-08-17 07:50:33
【问题描述】:

我在 c++ 中有一个简单的 for 循环

int makeAnagram(string a, string b)
{
  int deletionCnt = 0;
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());

  string::iterator itrA = a.begin();
  string::iterator itrB = b.begin();

  for (itrA; (itrA != a.end() && itrB != b.end()); itrA++)
  {
    if (*itrA < *itrB)
    {
      deletionCnt++;
    }
    else if (*itrA == *itrB)
    {
      itrB++;
    }
    else if (*itrA > *itrB)
    {
      deletionCnt++;
      itrB++;
    }
    else if (itrA == a.end())
    {
      deletionCnt += (b.end() - itrB);
      itrB = b.end();
    }
    else if (itrB == b.end())
    {
      deletionCnt += (a.end() - itrA);
      itrA = a.end();
    }
    else
    {
      cout << "Additional condition not checked : ";
    }
  }

  cout << "itrA is " << *itrA << ","
       << " itrB is " << *itrB << endl;
  return deletionCnt;
}

直到itrAitrB 都到达终点时,此循环才会运行,而是当其中一个到达终点时循环结束。

我的理解是两个迭代器都应该指向结尾,因为那是循环条件。

谁能解释一下?

谢谢你,干杯!

【问题讨论】:

  • 提供重现问题的最小完整程序。
  • 循环条件完全按照它说的做。只要两个迭代器都没有结束,它就会循环。也就是如果一个到达终点,条件为假,循环退出。
  • 更改为!(itrA == a.end() &amp;&amp; itrB == b.end())
  • 要小心,因为如果您更改循环条件以使循环在一个迭代器到达末尾时继续,那么取消引用该迭代器将导致未定义的行为,并且您需要检查 before 在前三个 if 条件中取消引用迭代器。

标签: c++ for-loop iterator


【解决方案1】:

您的代码运行正常。循环终止的条件是itrA != a.end() &amp;&amp; itrB != b.end()。如果任一迭代器已经结束,and 子句将返回 false 并且循环将终止。

如果您希望循环在两个迭代器都结束时终止,您可以使用!(itrA == a.end() &amp;&amp; itrA == a.end()) 之类的条件。请注意,如果您继续将任一迭代器移出范围,这将不起作用。

【讨论】:

    【解决方案2】:

    如果itrA没有到达终点,则条件(itrA != a.end()为真。

    (itrA == a.end() 为真,如果 itrA 确实 到达终点。

    A和B都到达终点的正确条件是(itrA == a.end() &amp;&amp; itrB == b.end())

    【讨论】:

    • 此逻辑适用于while 循环。 for 循环怎么样?
    • 我认为while 循环和for 循环在语义上是等价的。
    猜你喜欢
    • 2019-08-29
    • 2020-09-09
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    相关资源
    最近更新 更多