简体   繁体   中英

Why I can't see any ouput iterating this vector?

This is my code :

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
using std::printf;

int main()
{
    std::vector<int> array{1, 2, 3, 4, 5};   

    for(auto i = array.begin(); i != array.end(); i++) {
        auto index = i - array.begin();

        if(array[index] == 2 || array[index] == 5) {
            i = array.erase(i);
        }

        printf("iteration | %ld\n", index);
    }   
}

why I can't get any output from this? Using cout instead of printf works...

When you are erasing 5 , i = array.erase(i); will leave the iterator at end() . But then you do i++ which moves past the end, causing undefined behaviour.

To fix this, change your logic so that i++ only occurs for iterations where i = array.erase(i); did not occur.


Note: You could just write *i == 2 || *i == 5 *i == 2 || *i == 5 instead of having index

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