简体   繁体   English

为什么我看不到任何迭代此向量的输出?

[英]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... 使用cout代替printf可以工作...

When you are erasing 5 , i = array.erase(i); 当您擦除5i = array.erase(i); will leave the iterator at end() . 将迭代器保留在end() But then you do i++ which moves past the end, causing undefined behaviour. 但是,然后您执行i++ ,它就结束了,从而导致不确定的行为。

To fix this, change your logic so that i++ only occurs for iterations where i = array.erase(i); 要解决此问题,请更改逻辑,以使i++仅出现在其中i = array.erase(i);迭代中i = array.erase(i); did not occur. 没有发生。


Note: You could just write *i == 2 || *i == 5 注意:您可以只写*i == 2 || *i == 5 *i == 2 || *i == 5 instead of having index *i == 2 || *i == 5而不是index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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