只有在其中一个迭代器到达末尾后,循环才会退出。这里有什么问题?

The loop exits only after one of the iterator has reached the end. What is wrong here?

我在 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 没有到达终点,条件 (itrA != a.end() 为真。

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

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

您的代码运行正常。循环终止的条件是itrA != a.end() && itrB != b.end()。如果任一迭代器已到达其末尾,则 and 子句将为 return false 并且循环将终止。

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