简体   繁体   中英

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. 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);

In that final for loop, you check for it == end() , then increment. 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.

Add another check for end() with reset back to begin() after the for loop.

I have to add that this use of iterators is a little strange. There's probably a better approach than repeatedly incrementing m. What are you trying to do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM