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. If you erase the last element in nums
, it
would point at nums.end()
. You don't verify that it
is not pointing at end()
so you get the error.
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);