【发布时间】: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;
}
直到itrA 和itrB 都到达终点时,此循环才会运行,而是当其中一个到达终点时循环结束。
我的理解是两个迭代器都应该指向结尾,因为那是循环条件。
谁能解释一下?
谢谢你,干杯!
【问题讨论】:
-
提供重现问题的最小完整程序。
-
循环条件完全按照它说的做。只要两个迭代器都没有结束,它就会循环。也就是如果一个到达终点,条件为假,循环退出。
-
更改为
!(itrA == a.end() && itrB == b.end()) -
要小心,因为如果您更改循环条件以使循环在一个迭代器到达末尾时继续,那么取消引用该迭代器将导致未定义的行为,并且您需要检查 before 在前三个
if条件中取消引用迭代器。