gpt4 book ai didi

c++ - vector 迭代器不可递减?

转载 作者:行者123 更新时间:2023-11-28 06:21:31 25 4
gpt4 key购买 nike

有人能解释一下为什么这个代码片段会在循环中运行一次,然后给出断言失败表达式: vector 迭代器不可递减吗?

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 if 你知道它们将属于完全相同的类型:

for (auto an = a.rbegin(), bn = b.rbegin(); ...

关于c++ - vector 迭代器不可递减?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29225448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com