[英]C++ vector iterator errors
I'm just learning how to use iterators over vectors, and I'm having some trouble with run-time errors. 我只是学习如何在向量上使用迭代器,而且我在运行时错误方面遇到了一些麻烦。 Here's the section of code:
这是代码部分:
vector<int> nums;
for (int i=0; i<N; i++) { nums.push_back(i+1); }
vector<int>::iterator it = nums.begin();
while(nums.size() > 1)
{
//cout << *it << " ";
it = nums.erase(it);
for (int i=0; i<m-1; i++)
{
if (it == nums.end())
it = nums.begin();
else
++it;
}
}
The commented-out line gives me a "vector iterator is not dereferencable" error, which I think has to do with the iterator reaching the end, and I also get a "vector erase iterator outside range" error, though I've tried to account for that with the statement 注释掉的行给了我一个“向量迭代器不可解除错误”的错误,我认为它与迭代器到达终点有关,而且我也得到了一个“向量擦除迭代器超出范围”的错误,尽管我试过用声明说明这一点
if (it == nums.end()) it = nums.begin();
to no avail. 无济于事。 I've also gotten some "vector iterator not incrementable" errors, which I've found have to do with using the erase function, but I used
我也得到了一些“矢量迭代器不可递增”的错误,我发现它与使用擦除功能有关,但我用过
it = nums.erase(it);
to account for the invalidated iterator, which is the only advice I could find anywhere online. 考虑到无效的迭代器,这是我在网上找到的唯一建议。
I'm trying to have the iterator sweep through the vector multiple times, erasing specific values on each pass until only one is left (the code I posted is actually looped several times). 我试图让迭代器多次扫描向量,在每次传递中擦除特定值,直到只留下一个(我发布的代码实际上已循环多次)。 If you guys have any suggestions to eliminate these errors or can explain where they're coming from, I'd really appreciate it :)
如果你们有任何建议消除这些错误或者可以解释它们的来源,我真的很感激:)
Thanks, 谢谢,
Chris 克里斯
When you use: 当你使用:
it = nums.erase(it);
it
is set to the element following the erased one. it
被设置为擦除后的元素。 If you erase the last element in nums
, it
would point at nums.end()
. 如果删除
nums
的最后一个元素, it
指向nums.end()
。 You don't verify that it
is not pointing at end()
so you get the error. 您没有验证
it
是否指向end()
因此您收到错误。
Since you didn't explain what logic you're trying to achieve, I won't dig into it. 既然你没有解释你想要达到的逻辑,我就不会深入研究它。 I'm just suggesting you add an iterator validation before erasing elements, that is:
我只是建议你在删除元素之前添加一个迭代器验证,即:
if (it != nums.end())
it = nums.erase(it);
In that final for
loop, you check for it == end()
, then increment. 在最后的
for
循环中,检查it == end()
, 然后递增。 That means in some cases, it
can be pointing to the final element (not equal to end()
), then get incremented, so that it is now equal to end()
, and that's how the next while
iteration is started. 这意味着,在某些情况下,
it
可以指向最后一个元素(不等于end()
然后得到增加,所以它现在是等于end()
这是在未来如何while
迭代开始。
Add another check for end()
with reset back to begin()
after the for loop. 添加另一个
end()
检查,并在for循环后重置为begin()
。
I have to add that this use of iterators is a little strange. 我必须补充一点,这种迭代器的使用有点奇怪。 There's probably a better approach than repeatedly incrementing m.
有可能比重复递增m更好的方法。 What are you trying to do?
你想做什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.