有人可以阐明为什么此代码段将通过循环运行一次,然后给出断言失败的原因表达式:向量迭代器不可递增?
for (auto an = a.rbegin(); an != a.rend(); ++an, indexA--) //first number
{
for (auto bn = b.rbegin(); bn != b.rend(); ++bn) //second number
{
if (*an - *bn >= 0)
{
returnVal.push_back(*an - *bn);
a.pop_back();
b.pop_back();
}
else
{
brrow = *an + 10;
a.at(indexA - 1) = a.at(indexA - 1) - 1; // remove 1 from the spot ahead of current digit
returnVal.push_back(brrow - *bn);
a.pop_back();
b.pop_back();
}
}
}
最佳答案
根据您的评论,似乎您希望一前一后地遍历两个迭代器范围-仅需要一个for
循环,如下所示:
auto an = a.rbegin();
for (auto bn = b.rbegin();
an != a.rend() && bn != b.rend();
++an, ++bn, indexA--)
if (*an - *bn >= 0)
returnVal.push_back(*an - *bn);
else
{
brrow = *an + 10;
--(a.at(indexA - 1)); // remove 1 from the spot ahead of current digit
// shouldn't you check for rend() first????
returnVal.push_back(brrow - *bn);
}
请注意,如果您知道两个迭代器的类型完全相同,则可以将它们声明为
for
-loop local。for (auto an = a.rbegin(), bn = b.rbegin(); ...